gpt4 book ai didi

c# - 匿名类的 DisplayNameAttribute

转载 作者:太空狗 更新时间:2023-10-29 19:43:10 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com