Why is DataAnnotations ignored when using a DataGrid with AutoGenerateColumns=“True”

后端 未结 3 1709
迷失自我
迷失自我 2021-02-06 12:27

I\'m using the WPF DataGrid to bind to a collection of a custom class. Using AutoGenerateColumns=\"True\" in the grid XAML, the grid is created and populated just fine, but the

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 12:47

    Using @Marc's suggestion was the beginning of the solution, but taken on it's own, the AutoGenerated columns still have the property names as headings.

    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 specify ShortName:

    Public Class modelQ016
        
        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 changes, so you must use the GetType(...) instead of a numeric parameter... Such fun!

提交回复
热议问题