C# Datagrid将rowloading事件附加到项目中的所有Datagrid
我想将一个特定的C# Datagrid将rowloading事件附加到项目中的所有Datagrid,c#,wpf,C#,Wpf,我想将一个特定的行加载事件附加到项目中所有数据网格中的所有数据网格(大约有20个)。活动内容如下: private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = (e.Row.GetIndex() + 1).ToString(); } 我想在项目启动时附加以下事件: RegisterClassHandler(typeof(DataGrid)、Da
行加载
事件附加到项目中所有数据网格中的所有数据网格
(大约有20个)。活动内容如下:
private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}
我想在项目启动时附加以下事件:
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
中发生的事情,以防您的问题只是关于标题中的行索引,您不需要处理LoadingRow
事件。相反,您可以使用对属性的绑定:
<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>
绑定转换器如下所示:
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();
}
}
我认为是这样。您可以通过反射找到所有DataGrid实例并访问它们的事件处理程序。但这将是一个非常肮脏的解决方案。
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();
}
}