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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM