DisplayNameAttribute for anonymous class

If I had a non-anonymous class, I know that I can use DisplayNameAttribute like this.

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

but I

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

and I use records for DataSource for DataGrid. The column headings appear as Foo and Bar , but they should be The Foo and The Bar . I cannot create a specific class for several different internal reasons, and it must be an anonymous class. Given this, can I still set DisplayNameAttrubute for members of this anonymous class?

I tried

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

but it will not compile.

Thanks.

+8
c # anonymous-types
source share
2 answers

How about the following solution:

 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(); 

Then you have the following property code attached:

 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]; } } } 
+2
source share

As far as I know, you cannot apply an attribute to an anonymous type. The compiler just does not support it. You could leave the van and use something like Mono.Cecil as a step after assembly to put the attribute here, but this is hardly what you want to consider. Why should it be anonymous?

+2
source share

All Articles