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;
 }

实现的效果

相关推荐
西西弗Sisyphus1 小时前
C++ explicit 关键字工程实践
开发语言·c++
郝学胜-神的一滴2 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
feixing_fx3 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
wuyk5553 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
zdr尽职尽责3 小时前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
神明不懂浪漫3 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
yiangL_4 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
山楂树の7 小时前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记
利威尔xu7 小时前
2026-11-18-Go接口幂等设计实战
开发语言·后端·golang
宝桥南山7 小时前
Visual Studio 2026新特性 - 可以直接连接DeepSeek(使用Custom Endpoint Provider配置项)
ide·microsoft·微软·aigc·.net·visual studio