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

实现的效果

相关推荐
流星白龙2 分钟前
【C++算法】69.栈_验证栈序列
开发语言·c++·算法
Luis Li 的猫猫16 分钟前
MATLAB跳动的爱心
开发语言·算法·matlab
AIGC魔法师35 分钟前
AI 极客低代码平台快速上手 --生成Python代码
开发语言·harmonyos·低代码平台·ai极客
熊猫钓鱼>_>1 小时前
对话即编程:如何用 Trae 的 @智能体 5 分钟修复一个复杂 Bug?
开发语言·python·bug
搏博1 小时前
WPS JS宏实现去掉文档中的所有空行
开发语言·javascript·wps
hie988941 小时前
MATLAB中进行语音信号分析
开发语言·matlab·语音识别
前进的程序员1 小时前
C++经典库介绍
开发语言·c++
(・Д・)ノ2 小时前
python打卡day31
开发语言·人工智能·python
北漂老男孩2 小时前
JavaScript 性能优化实战指南
开发语言·javascript·性能优化
yorushika_2 小时前
python打卡训练营打卡记录day31
开发语言·python·机器学习