WPF:DataGrid 自动生成行号

本文介绍了一种简单的方法来为WPF中的DataGrid自动生成行号。仅需使用一个ValueConverter,即可轻松实现在DataGridRowHeader中显示行号。示例提供了完整的代码实现。

  下面给大家分享一种通过 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值