wpf之datagrid 序号列

本文介绍了在Windows应用程序中使用DataGridView(datagrid)添加序列号的方法,包括在数据行加载时动态设置、创建模板列以及通过设置HeadersVisibility隐藏首列。最后提到使用HeadersVisibility属性可以达到更好的视觉效果。
摘要由CSDN通过智能技术生成

方法一:在datagrid最前面添加序列号
窗体加载时:

<span style="font-family:KaiTi_GB2312;font-size:24px;">private void MdiChild_Loaded(object sender, RoutedEventArgs e)
        {
            dgData.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow);
            dgData.UnloadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_UnLoadingRow);
        }

 public void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

public  void dataGrid_UnLoadingRow(object sender, DataGridRowEventArgs e)
        {
            dataGrid_LoadingRow(sender, e);
            if (dgData.Items != null)
            {
                for (int i = 0; i < dgData.Items.Count; i++)
                {
                    try
                    {
                        DataGridRow row = dgData.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
                        if (row != null)
                        {
                            row.Header = (i + 1).ToString();
                        }
                    }
                    catch { }
                }
            }
        }</span>


结果:

 

缺点:没有标识“序号”二字。

方法二:在datagrid中添加一列,用来放置序列号

界面上的代码:

<span style="font-family:KaiTi_GB2312;font-size:24px;"><DataGrid>
<DataGrid.Columns>    
          <DataGridTemplateColumn Header=" 序号" Width="50" MinWidth="10" IsReadOnly="True">
                   <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0"></TextBlock>
                            </DataTemplate>
                   </DataGridTemplateColumn.CellTemplate>
         </DataGridTemplateColumn>
         <DataGridTextColumn Binding="{Binding Name}" Width="*" Header="账套名称" IsReadOnly="True" />
</DataGrid.Columns> 
</DataGrid></span>

后台添加一个datagrid的【LoadingRow】方法:
 

 private void dgData_LoadingRow(object sender, DataGridRowEventArgs e)
 {
       e.Row.Header = e.Row.GetIndex() + 1;
 }</span>

结果:

缺点:有缺陷,怎么回事?是因为datagrid的【LoadingRow】方法的存在,若这个方法去掉,则序号也不显示了。最终想了个折中的办法,将最前面的那一个序号列隐藏掉。

方法:在datagrid中加上一个属性【HeadersVisibility="Column" 】,OK,结果完美出现。

没有了最前面的那个边框,反而更好看了。

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值