给WPF的DataGrid添加行号的方法(在XAML中添加,不是添加到行最前面那种)

 <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Header, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}, Mode=FindAncestor}}"
               Header="序号" CanUserSort="False"   IsReadOnly="True" Width="0.5*">
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>

以上这种加行号的方法就不用在后台加如下这个函数就可以自动生成行号了(而且可以在任意列生成行号)

 private void gdView_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF DataGrid 添加行号,可以使用以下两种方法: 1. 在 XAML 定义行号列 可以在 DataGrid 添加一个新列,用于显示行号。在 XAML ,可以使用 DataGridTemplateColumn 和 MultiBinding 来实现,如下所示: ```xml <DataGrid x:Name="dataGrid1"> <DataGrid.Columns> <DataGridTemplateColumn Header="#" Width="50"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=Items.IndexOf(this) + 1}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <!-- 其他列 --> </DataGrid.Columns> </DataGrid> ``` 上述代码,定义了一个名为“#”的 DataGridTemplateColumn,宽度为50。该列的单元格使用 TextBlock 来显示行号,Text 属性绑定到 Items.IndexOf(this) + 1,表示当前在 Items 集合的索引值加1,即为行号。 2. 在代码添加行号列 可以在代码处理 DataGrid 的 LoadingRow 事件,为每一添加一个新的列,用于显示行号。如下所示: ```csharp private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = (e.Row.GetIndex() + 1).ToString(); } ``` 上述代码,使用 LoadingRow 事件处理程序为每一添加一个头,头的内容为当前DataGrid 的索引值加1。需要注意的是,需要将 DataGrid 的 RowHeadersVisible 属性设置为 true,才能显示头。可以在 XAML 或者在代码设置该属性,如下所示: ```csharp dataGrid1.RowHeadersVisible = true; ``` ```xml <DataGrid x:Name="dataGrid1" RowHeadersVisible="True"> <!-- 其他列 --> </DataGrid> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值