WPF DataGrid 自动生成行号的方法(通过修改RowHeaderTemplate的方式)

WPF中的DataGrid自动生成行号的方法有很多,这里记录了一种通过修改 RowHeaderTemplate的方式来生成行号:

方法一:

xaml界面:

<Window
    ...
    xmlns:local="clr-namespace:Test"
    DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
    <Window.Resources>
        <local:RowToIndexConv x:Key="RowToIndexConv"/>
    </Window.Resources>
        <DataGrid ItemsSource="{Binding GridData}">
            <DataGrid.RowHeaderTemplate>
                <DataTemplate>
                    <TextBlock Margin="2" Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Converter={StaticResource RowToIndexConv}}"/>
                </DataTemplate>
            </DataGrid.RowHeaderTemplate>
        </DataGrid>
</Window>

其中的Converter代码:

public class RowToIndexConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DataGridRow row = value as DataGridRow;
        return row.GetIndex() + 1;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

这样就ok了。。

这种方法的好处是方便更好的自定义表头样式

还有一个作者也觉得好用的方法,是通过为DataGrid添加一个Behavior,但是这个方法不好扩展表头的样式。

方法二:

public class DataGridShowRowIndexBehavior
{
    public static bool GetShwoRowIndex(DependencyObject obj)
    {
        return (bool)obj.GetValue(ShowRowIndexProperty);
    }

    public static void SetShowRowIndex(DependencyObject obj,bool value)
    {
        obj.SetValue(ShowRowIndexProperty,value);
    }

    public static readonly DependencyProperty ShowRowIndexProperty = DependencyProperty.RegisterAttached("ShowRowIndex",typeof(bool),typeof(DataGridShowRowIndexBrhavior),new UIPropertyMetaData(false,ShowRowIndexPropertyChanged));

    private static void ShowRowIndexPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
    {
        var dataGrid= d as DataGrid;
        if (dataGrid==null) return ;
        dataGrid.LoadingRow+=
            delegate(object sender,DataGridRowEventArgs e1)
                {
                    e1.Row.Header=e1.Row.GetIndex()+1;
                };
    }
  
}

然后在DataGrid上添加该Behavior就可以了。

<DataGrid Behavior:DataGridShowRowIndexBehavior.ShowRowIndex="True"/>

但是这个方法就只能显示出来,要是表头想在数字后面加一个图片,这就没第一种方法好用了。

欢迎转载,请注明来自Leaco的博客http://www.cnblogs.com/Leaco/p/3191294.html 

欢迎转载,转载请注明来自 Leaco 的博客:http://www.cnblogs.com/Leaco
原文地址:https://www.cnblogs.com/Leaco/p/3191294.html