WPF DataGrid自动增长序号列
/// <summary> /// 自动增长序号列 /// </summary> public class DataGridRowIndexColumn : DataGridTextColumn { /// <summary> /// 可以指定开始序号 /// </summary> public int StartIndex { get { return (int)GetValue(StartIndexProperty); } set { SetValue(StartIndexProperty, value); } } public static readonly DependencyProperty StartIndexProperty = DependencyProperty.Register("StartIndex", typeof(int), typeof(DataGridRowIndexColumn), new FrameworkPropertyMetadata(0, propertyChangedCallback: StartIndexChanged)); private static void StartIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var column = (DataGridRowIndexColumn)d; if (e.OldValue == e.NewValue) return; int v = (int)e.NewValue; if (column.DataGridOwner == null) return; IList list = column.DataGridOwner.Items; TextBlock ele = null; int i = 0; foreach (object item in list) { ele = column.GetCellContent(item) as TextBlock; ele.Text = (v + i).ToString(); i++; } } protected override void RefreshCellContent(FrameworkElement element, string propertyName) { base.RefreshCellContent(element, propertyName); } protected override bool OnCoerceIsReadOnly(bool baseValue) { return true; } protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock text = (TextBlock)base.GenerateElement(cell, dataItem); int index = (DataGridOwner.Items as IList).IndexOf(dataItem); text.Text = (index + StartIndex).ToString(); //https://www.cnblogs.com/RedSky/p/18215093 TypeUtil.InvokeMethod(this, typeof(DataGridColumn), "ApplyStyle", new Type[] { typeof(bool), typeof(bool), typeof(FrameworkElement) }, new object[] { false, false, text }); return textBox; } }
调用方式:
<DataGrid ItemsSource="{Binding Mods}" AutoGenerateColumns="False"> <DataGrid.Columns> <local:DataGridRowIndexColumn Binding="{Binding Sort}" StartIndex="20"/> <DataGridTextColumn Binding="{Binding Name}"/> </DataGrid.Columns> </DataGrid>