WPF的DataGrid自动生成中文列头

直接将一个对象集合绑定到DataGrid上面,设置自动生成列AutoGenerateColumns="True",DataGrid会自动根据对象类的属性生成对应的列

示例类对象:

C# 复制代码
 public class DataModel
 {
     public int Id { get; set; }

     public string Name { get; set; }

     public string Description { get; set; }

     public string Username { get; set; }

     public string Password { get; set; }
 }

绑定到DataGrid的ItemsSource上面,的效果如下:

自动生成中文表头

如果要生成中文表头,常规的做法就是在Xaml写完整每个表头,Header等于中文表头名,然后一一绑定属性,这样表头就是固定的,并且比较麻烦。

现在想要的就是在自动生成的时候把属性表头自动转换成中文的表头,通过添加特性标签来实现。

1. 在类的属性上增加特性用于标示对应的中文

Description特性对属性都添加中文描述(也可以使用其他特性比如Display,后面查找的时候改成对应的就可以了)

C# 复制代码
 public class DataModel
 {
     [Description("ID编号")]
     public int Id { get; set; }

     [Description("姓名")]
     public string Name { get; set; }

     [Description("描述")]
     public string Description { get; set; }

     [Description("用户名")]
     public string Username { get; set; }

     [Description("密码")]
     public string Password { get; set; }
 }

2. 添加AutoGeneratingColumn事件

在DataGrid上面添加AutoGeneratingColumn事件,在生成留过程中替换列头Header,AutoGeneratingColumn="DG_AutoGeneratingColumn"

C# 复制代码
 private void DG_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
 {
     var result = e.PropertyName;
     var p = (e.PropertyDescriptor as PropertyDescriptor)
         .ComponentType.GetProperties()
         .FirstOrDefault(x => x.Name == e.PropertyName);
     if (p != null)
     {
         var found = p.GetCustomAttribute<DescriptionAttribute>();
         if (found != null)
             result = found.Description;
     }
     e.Column.Header = result;
 }

实现的效果

相关推荐
雨落倾城夏未凉4 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫5 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫6 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6256 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902116 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠7 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫9 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech9 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf11 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m62511 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#