如果我有一个像这样的非匿名类,我知道我可以像这样使用 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
。列标题显示为 Foo
和 Bar
,但它们必须是 The Foo
和 The 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/