如果我有这样的非匿名类,我知道我可以使用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/

10-12 01:57