c# - 匿名类的 DisplayNameAttribute

标签 c# anonymous-types

如果我有一个像这样的非匿名类,我知道我可以像这样使用 DisplayNameAttribute

class Record{

    [DisplayName("The Foo")]
    public string Foo {get; set;}

    [DisplayName("The Bar")]
    public string Bar {get; set;}

}

但是我有

var records = (from item in someCollection
               select{
                   Foo = item.SomeField,
                   Bar = item.SomeOtherField,
               }).ToList();

并且我将 records 用于 DataGrid 的 DataSource。列标题显示为 FooBar,但它们必须是 The FooThe Bar。由于一些不同的内部原因,我无法创建一个具体类,它必须是一个匿名类。鉴于此,我是否可以为这个匿名类的成员设置 DisplayNameAttrubute

我试过了

[DisplayName("The Foo")] Foo = item.SomeField

但它不会编译。

谢谢。

最佳答案

下面的解决方案怎么样:

dataGrid.SetValue(
    DataGridUtilities.ColumnHeadersProperty,
    new Dictionary<string, string> {
        { "Foo", "The Foo" },
        { "Bar", "The Bar" },
    });

dataGrid.ItemsSource = (from item in someCollection
           select{
               Foo = item.SomeField,
               Bar = item.SomeOtherField,
           }).ToList();

然后你有以下附加属性代码:

public static class DataGridUtilities
{
    public static IDictionary<string,string> GetColumnHeaders(
        DependencyObject obj)
    {
        return (IDictionary<string,string>)obj.GetValue(ColumnHeadersProperty);
    }

    public static void SetColumnHeaders(DependencyObject obj,
        IDictionary<string, string> value)
    {
        obj.SetValue(ColumnHeadersProperty, value);
    }

    public static readonly DependencyProperty ColumnHeadersProperty =
        DependencyProperty.RegisterAttached(
            "ColumnHeaders",
            typeof(IDictionary<string, string>),
            typeof(DataGrid),
            new UIPropertyMetadata(null, ColumnHeadersPropertyChanged));

    static void ColumnHeadersPropertyChanged(DependencyObject sender,
        DependencyPropertyChangedEventArgs e)
    {
        var dataGrid = sender as DataGrid;
        if (dataGrid != null && e.NewValue != null)
        {
            dataGrid.AutoGeneratingColumn += AddColumnHeaders;
        }
    }

    static void AddColumnHeaders(object sender,
        DataGridAutoGeneratingColumnEventArgs e)
    {
        var headers = GetColumnHeaders(sender as DataGrid);
        if (headers != null && headers.ContainsKey(e.PropertyName))
        {
            e.Column.Header = headers[e.PropertyName];
        }
    }
}

关于c# - 匿名类的 DisplayNameAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6219619/

相关文章:

c# - 将字符串数组中的值分配给自定义类型数组的每个元素的字符串属性

c# - 使用自定义属性获取所有字段 - 包括继承的字段

go - go 'Template.Execute'如何读取其匿名结构的参数字段?

c# - 在 View 中访问动态匿名类型时出现 RuntimeBinderException

c# - C#如何将一个变量名变成一个匿名对象的属性名?

c# - 如何声明 C# 匿名类型而不创建它的实例?

c# - 将变量转换为仅在运行时已知的类型?

c# - 如何解决 Gen2 堆碎片

c# - 如何使用 LINQ to XML 将 List<T> 序列化为 XML?

java - 为什么会出现 "No suitable method found for anonymous "错误?