Why DataAnnotations <Display (Name: = "My Name")> is ignored when using a DataGrid with AutoGenerateColumns = "True"
I am using WPF DataGrid to bind to a custom class collection. Using AutoGenerateColumns = "True" in the XAML grid, the grid is created and filled just fine, but the headers are property names, as you would expect.
I tried to specify
<Display(Name:="My Name")> from the System.ComponentModel.DataAnnotations namespace and has no effect. I also tried
<DisplayName("My Name")> from the System.ComponentModel namespace, but still the headers are not affected.
Is there no way to specify column headers with the AutoGenerateColumns parameter?
Using the @Marc clause was the beginning of the solution, but taken care of, AutoGenerated columns still have property names as headers.
To get the DisplayName, you need to add a routine (in the code behind) to handle the GridAutoGeneratingColumn event:
Private Sub OnGeneratingColumn(sender As Object, e As System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs) Handles Grid.AutoGeneratingColumn Dim pd As System.ComponentModel.PropertyDescriptor = e.PropertyDescriptor e.Column.Header = pd.DisplayName End Sub An additional and better solution is to use the ComponentModel.DataAnnotations namespace and specifying ShortName:
Public Class modelQ016 <Display(shortname:="DB Name")> Public Property DBNAME As String ... OnGeneratingColumn becomes:
Dim pd As System.ComponentModel.PropertyDescriptor = e.PropertyDescriptor Dim DisplayAttrib As System.ComponentModel.DataAnnotations.DisplayAttribute = pd.Attributes(GetType(ComponentModel.DataAnnotations.DisplayAttribute)) If Not DisplayAttrib Is Nothing Then e.Column.Header = DisplayAttrib.ShortName End If Note that the order of the attributes in the attribute array changes, so you should use GetType (...) instead of a numeric parameter ... Such a pleasure!
Using the @GilShalit post, this is what you need to add if you are using Resources (as you probably should support multi-language support) in C # at this time
Declaration of your property with annotation
[Display(ResourceType = typeof (YourStronglyTypedMessagesResource), Name = "YourGridColumnName")] public string Column1 { get; set; } Event handler
private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { var pd = (PropertyDescriptor)e.PropertyDescriptor; var atb = (DisplayAttribute)pd.Attributes[typeof(DisplayAttribute)]; if (atb != null) { e.Column.Header = atb.GetName(); } } You can try the older System.ComponentModel.DisplayNameAttribute . In C #, [DisplayName("My Name")] . In particular, this works with a PropertyDescriptor that reinforces a lot of data binding.