示例:WPF中应用DataGrid读取实体DisplayAttribute特性自动自动生成列名

一、目的:通过重写DataGrid的OnAutoGeneratingColumn方法实现根据定义特性自动生成列头信息功能

二、实现

cs 复制代码
<DataGrid ItemsSource="{local:GetStudents Count=50}"/>

实体定义如下

cs 复制代码
 public class Student
 {
     [DataGridColumn("*")]
     [Display(Name = "姓名", GroupName = "基础信息")]
     [Required]
     public string Name { get; set; }

     [DataGridColumn("*")]
     [Display(Name = "班级", GroupName = "基础信息")]
     [Required]
     public string Class { get; set; }

     [DataGridColumn("2*")]
     [Display(Name = "地址", GroupName = "基础信息")]
     [Required]
     public string Address { get; set; }

     [DataGridColumn("2*")]
     [Display(Name = "邮箱", GroupName = "基础信息")]
     [Required]
     public string Emall { get; set; }

     [Display(Name = "可用", GroupName = "其他信息")]
     [Required]
     public bool IsEnbled { get; set; }

     [Display(Name = "时间", GroupName = "其他信息")]
     [Required]
     public DateTime Time { get; set; }

     [Display(Name = "年龄", GroupName = "基础信息")]
     [Required]
     public int Age { get; set; }

     [Display(Name = "分数", GroupName = "成绩信息")]
     public double Score { get; set; }

     [DataGridColumn("2*")]
     [Display(Name = "电话号码", GroupName = "基础信息")]
     [Required]
     [RegularExpression("^1[3|4|5|7|8][0-9]{9}$", ErrorMessage = "手机号码不合法!")]
     public string Tel { get; set; }
 }

通常如上定义会生成一个根据属性名称列头的表格

三、环境

VS2022

四、示例

自定义一个DislayDataGrid,重写OnAutoGeneratingColumn方法

cs 复制代码
    public class DislayDataGrid : DataGrid
    {
        protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
        {
            base.OnAutoGeneratingColumn(e);
            if (e.PropertyDescriptor is PropertyDescriptor descriptor)
                e.Column.Header = descriptor.Attributes.OfType<DisplayAttribute>()?.FirstOrDefault().Name;
        }
    }

此时会根据读取特性生成中文名称列头

同理其他属性也可以这样设置

我们扩展一个特性DataGridColumnAttribute

cs 复制代码
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public class DataGridColumnAttribute : Attribute, IDataGridColumn
    {
        public DataGridColumnAttribute(string width)
        {
            DataGridLengthConverter converter = new DataGridLengthConverter();
            this.Width = (DataGridLength)converter.ConvertFromString(width);
        }
        public DataGridColumnAttribute()
        {

        }
        public DataGridLength Width { get; set; } = DataGridLength.Auto;
        public Type Template { get; set; } = typeof(DataGridTextColumn);
        /// <summary>
        /// "{0}.Property"
        /// </summary>
        public string PropertyPath { get; set; } = "{0}";
        public virtual DataGridColumn GetDataGridColumn(PropertyInfo propertyInfo)
        {
            DataGridColumn dataGridColumn = Activator.CreateInstance(this.Template) as DataGridColumn;
            if (dataGridColumn == null)
            {
                if (propertyInfo.PropertyType == typeof(bool))
                {
                    return new DataGridCheckBoxColumn() { Width = this.Width, IsReadOnly = false };
                }
                else if (propertyInfo.PropertyType.IsEnum)
                {
                    return new DataGridComboBoxColumn() { Width = this.Width, IsReadOnly = false };
                }
                else
                {
                    return new DataGridTextColumn() { Width = this.Width, IsReadOnly = false };
                }
            }
            dataGridColumn.Width = this.Width;
            return dataGridColumn;
        }
    }

在生成列时应用该特性

此时列宽也根据特性变化

如果不想通过自定义DisplayDataGrid实现也可以用Behavior行为的方式实现

实现方式如下:

XML 复制代码
    <DataGrid ItemsSource="{h:GetStudents Count=50}">
        <b:Interaction.Behaviors>
            <h:DataGridAutoColumnBehavior Type="{x:Type h:Student}"/>
        </b:Interaction.Behaviors>
    </DataGrid>

DataGridAutoColumnBehavior的具体实现方式如下

WPF-Control/Source/Extensions/H.Extensions.Behvaiors/DataGrid/DataGridAutoColumnBehavior.cs at main · HeBianGu/WPF-Control · GitHub

这种方式在自动化生成表格数据中非常有用

五、需要了解的知识点

DataGrid.OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs) 方法 (System.Windows.Controls) | Microsoft Learn

DataGrid 类 (System.Windows.Controls) | Microsoft Learn

六、源码地址

GitHub - HeBianGu/WPF-ControlDemo: 示例

GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库

GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库

七、了解更多

System.Windows.Controls 命名空间 | Microsoft Learn

https://github.com/HeBianGu

HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频

相关推荐
程序员小刘1 小时前
【HarmonyOS 5】教育开发实践详解以及详细代码案例
华为·wpf·harmonyos
Java Fans15 小时前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
布伦鸽1 天前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
code bean2 天前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf
沉到海底去吧Go2 天前
【图片识别改名】如何批量将图片按图片上文字重命名?自动批量识别图片文字并命名,基于图片文字内容改名,WPF和京东ocr识别的解决方案
ocr·wpf·图片识别改名·图片识别重命名·图片内容改名
lph19722 天前
自定义事件wpf
wpf
code bean2 天前
【WPF】从普通 ItemsControl 到支持筛选的 ItemsControl:深入掌握 CollectionViewSource 用法
wpf
碎碎念的安静3 天前
WPF可拖拽ListView
c#·wpf
界面开发小八哥3 天前
界面组件DevExpress WPF中文教程:Grid - 如何识别行和卡片?
.net·wpf·界面控件·devexpress·ui开发
TwilightLemon4 天前
WPF 使用CompositionTarget.Rendering实现平滑流畅滚动的ScrollViewer,支持滚轮、触控板、触摸屏和笔
wpf