. Net – why ignore dataannotations when using a DataGrid with autogeneratecolumns = “true”
I'm using WPF DataGrid to bind to a collection of custom classes Using autogeneratecolumns = "true" in grid XAML, the grid is created and populated well, but the title is the attribute name, as expected
I tried to specify
<Display(Name:="My Name")>
From system ComponentModel. Dataannotations namespace, which has no effect I tried, too
<DisplayName("My Name")>
From system The componentmodel namespace, but the title is still unaffected
Can't you specify column headings using the autogeneratecolumns option?
Solution
The suggestion of using @ Marc is the beginning of the solution, but it adopts it itself. The autogenerated column still takes the attribute name as the title
To get the displayName, you need to add a routine (in the following code) to handle the gridautogenerating column 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
Another better solution is to use componentmodel Dataannotations namespace and specify 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 attributes in the attribute array will change, so you must use GetType (...) instead of numeric parameters... For fun!