[英]Datagrid attach rowloading event to all datagrids in project
我想將特定的RowLoading
事件附加到項目中所有數據網格中的所有DataGrid
中(它們大約有20個)。 事件是這樣的:
private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}
我想像這樣在項目啟動時附加事件: EventManager.RegisterClassHandler(typeof(DataGrid), DataGrid.LoadingRowEvent, new RoutedEventHandler(dataGrid_LoadingRow));
不幸的是, DataGrid.LoadingRowEvent
給出了錯誤,因為不存在具有該名稱的DataGrid類的事件。 但是,有一個具有該名稱的事件,我可以為每個網格手動添加該事件。 有什么方法可以在不使用自定義控件的情況下或在已使用過的任何地方更改DataGrid聲明的情況下執行此操作?
在WPF中, LoadingRow
事件未作為路由事件實現,因此您不能在EventManager
使用此技巧。 您不需要自定義控件。 只需派生DataGrid
類:
class MyDataGrid : DataGrid
{
protected override void OnLoadingRow(DataGridRowEventArgs e)
{
base.OnLoadingRow(e);
}
}
因此,在使用MyDataGrid
而不是DataGrid
類時,您可以完全控制OnLoadingRow
發生的OnLoadingRow
。
萬一您的問題僅與標題中的行索引有關,則無需處理LoadingRow
事件。 相反,您可以使用對AlternateIndex屬性的綁定:
<DataGrid AlternationCount="2147483647" ...>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Header"
Value="{Binding Path=(ItemsControl.AlternationIndex),
RelativeSource={RelativeSource Self},
Converter={StaticResource RowIndexConverter}}"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
您可以將其設置為默認的DataGrid
樣式,以便它自動應用於所有DataGrid實例:
<Style TargetType="DataGrid">
<Setter Property="AlternationCount" Value="2147483647"/>
<Setter Property="RowStyle">
<Setter.Value>
<Style TargetType="DataGridRow">
<Setter Property="Header"
Value="{Binding Path=(ItemsControl.AlternationIndex),
RelativeSource={RelativeSource Self},
Converter={StaticResource RowIndexConverter}}"/>
</Style>
</Setter.Value>
</Setter>
</Style>
綁定轉換器如下所示:
public class RowIndexConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("{0}", (int)value + 1);
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.