【问题标题】:WPF DataGrid - Can I decorate my POCOs with attributes to have custom column names?WPF DataGrid - 我可以用属性装饰我的 POCO 以具有自定义列名吗?
【发布时间】:2013-06-15 09:02:39
【问题描述】:

我在 WPF 中有一个 DataGrid,并用如下数据填充它:

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 在标题和 ComboCoxes 上显示它们(而不是变量名)。

类似这样的:

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

这可能吗?

【问题讨论】:

标签: wpf datagrid header


【解决方案1】:

好的。这是标题的方法:

您向您的属性添加属性,例如 Description 属性。

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

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

    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2020-01-24
    相关资源
    最近更新 更多