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

实现的效果

相关推荐
上位机付工38 分钟前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
励志不掉头发的内向程序员1 小时前
STL库——二叉搜索树
开发语言·c++·学习
至此流年莫相忘1 小时前
设计模式:模板方法模式
java·开发语言·设计模式
土了个豆子的2 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
疯狂的维修2 小时前
c#中public类比博图
c#·自动化
qq_172805592 小时前
Go 自建库的使用教程与测试
开发语言·后端·golang
久绊A2 小时前
Hydra-SSH 破解安全防范
开发语言·php
阿昭L2 小时前
c++中获取随机数
开发语言·c++
3壹2 小时前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
悟乙己2 小时前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n