WPF DataGrid - 我可以用属性来装饰我的 POCO 以获得自定义列名吗? [英] WPF DataGrid - Can I decorate my POCOs with attributes to have custom column names?

查看:25
本文介绍了WPF DataGrid - 我可以用属性来装饰我的 POCO 以获得自定义列名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WPF 中有一个 DataGrid 并用这样的数据填充它:

I have a DataGrid in WPF and fill it with data like this:

public enum Sharing
{
    Equal,
    SurfaceBased,
}

public class Data
{
    public bool Active { get; set; }
    public string Name { get; set; }
    public int Floor { get; set; }
    public Sharing Sharing { get; set; }
}
    public ObservableCollection<Data> _col = new ObservableCollection<Data>()
                                 {
                                  new Data(){Active = true, Name = "KRL", Floor = 0 },
                                  new Data(){Name = "DAT", Floor = 1},
                                  new Data(){Name = "TRE", Floor = 1},
                                  new Data(){Name = "DUO", Floor = 2},
                                 };

    public MainWindow()
    {
        InitializeComponent();

        grid.AutoGenerateColumns = true;
        grid.DataContext = _col;
        grid.ItemsSource = _col;
    }

我想知道是否可以在枚举和 POCO 类上使用一些属性,以便 DataGrid 在标题和 ComboCox 上显示它们(而不是变量名称).

I was wondering if I could use some attributes on the enumerations and the POCO class so that the DataGrid displays them (instead of the variable names) on the headers and ComboCoxes.

像这样:

public enum Sharing
{
    [Name("This is a test")]
    Equal,
    [Name("This is a test 2")]
    SurfaceBased,
}

这可能吗?

推荐答案

好的.这是为标题执行此操作的方法:

OK. Here is the way to do it for the Headers:

您向属性添加属性,例如 Description 属性.

You add attributes, like Description attributes to your Properties.

public class MyPOCO
{
    [Description("The amount you must pay")]
    public float Amount { get; set; }
}

然后,在从 DataGrid 派生的类中,您执行以下操作:

Then, in a class derived from DataGrid you do this:

    protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
    {
        try
        {
            base.OnAutoGeneratingColumn(e);
            var propDescr = e.PropertyDescriptor as System.ComponentModel.PropertyDescriptor;
            e.Column.Header = propDescr.Description;
        }
        catch (Exception ex)
        {
            Utils.ReportException(ex);
        }
    }

要为枚举成员添加自定义名称,您需要创建一个自定义列.你可以在这里看到一个简单的例子:https://stackoverflow.com/a/17510660/964053.

For adding custom names to the members of the enumerations, you need to make a custom column. You can see a simple example here : https://stackoverflow.com/a/17510660/964053.

这篇关于WPF DataGrid - 我可以用属性来装饰我的 POCO 以获得自定义列名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆