WPF:DataGrid 自动生成行号

  下面给大家分享一种通过 DataGridRowHeader 自动生成 DataGrid 数据行行号的方式。只需一个 ValueConverter 就能搞定。

  1. 值转换器
     1     class AutoNumberValueConverter : IMultiValueConverter
     2     {
     3         #region IMultiValueConverter 成员
     4 
     5         public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
     6         {
     7             var item = values[0];
     8             var items = values[1] as ItemCollection;
     9 
    10             var index = items.IndexOf(item);
    11             return (index + 1).ToString();
    12         }
    13 
    14         public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    15         {
    16             return null;
    17         }
    18 
    19         #endregion
    20     }
  2. 前台代码
     1 <Window x:Class="DataGridAutoRowNumberDemo.MainWindow"
     2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     4         xmlns:demo="clr-namespace:DataGridAutoRowNumberDemo"
     5         Title="MainWindow"
     6         Width="525"
     7         Height="350">
     8     <Window.Resources>
     9         <demo:AutoNumberValueConverter x:Key="autoNumberValueConverter" />
    10     </Window.Resources>
    11     <DataGrid x:Name="dataGrid">
    12         <DataGrid.RowHeaderStyle>
    13             <Style TargetType="{x:Type DataGridRowHeader}">
    14                 <Setter Property="Content">
    15                     <Setter.Value>
    16                         <MultiBinding Converter="{StaticResource autoNumberValueConverter}">
    17                             <Binding />
    18                             <Binding Path="Items" RelativeSource="{RelativeSource AncestorType={x:Type DataGrid}}" />
    19                         </MultiBinding>
    20                     </Setter.Value>
    21                 </Setter>
    22             </Style>
    23         </DataGrid.RowHeaderStyle>
    24     </DataGrid>
    25 </Window>

    就此搞定!
    示例代码:下载

原文地址:https://www.cnblogs.com/hoze/p/5103037.html