WPF DataGrid自动生成序号

需求和效果

应用WPF技术进行开发的时候,大多都会遇到给DataGrid添加序号的问题,今天分享一下查阅了很多stackoverflow的文章后,总结和改进过来的方法,先看一下效果图,文末附Demo下载链接

 

设计思想和代码

这里在DataGrid行级应用单值转换器,获取DataGrid的行号 , 转换为对应的序号,思路和实现非常简单,核心代码就几行

Binding:

                <DataGridTextColumn
                                    Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Converter={StaticResource rowToIndexConverter}}" />

Converter:

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DataGridRow row = value as DataGridRow;
            if (row != null)
                return row.GetIndex() + 1;
            else
                return -1;
        }

 

顺便一提,应用字典类型绑定DataGrid数据源,还是很方便的, 感兴趣的小伙伴可以一试 :)

                <DataGridTextColumn Header="姓名" 
                                    Binding="{Binding [Name]}" Width="60" />
                <DataGridTextColumn Header="年龄" 
                                    Binding="{Binding [Age]}" Width="60" />
                <DataGridTextColumn Header="时间"
                                    Binding="{Binding [Time]}" Width="60" />

 

下载

        链接: https://pan.baidu.com/s/1dE1dZPn

        密码: wa1v

 

posted @ 2017-10-19 10:49  _AlexYIN  阅读(2881)  评论(2编辑  收藏  举报