我使用WPF的DataGrid绑定到自定义类的集合。网格中的XAML使用的AutoGenerateColumns =真,网格创建并填充就好了,但标题是属性名称,如人们所期望的。
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 headings are the property names, as one would expect.
我试过,指定
<Display(Name:="My Name")>
从System.ComponentModel.DataAnnotations命名空间,并且没有任何影响。我也试过
from the System.ComponentModel.DataAnnotations namespace and that has no effect. I also tried
<DisplayName("My Name")>
从System.ComponentModel命名空间,但仍标题不受影响。
from the System.ComponentModel name space but still the headings are not affected.
请问有没有办法来指定列标题用的AutoGenerateColumns选项?
Is there no way to specify column headings with the AutoGenerateColumns option?
使用@马克的建议是该解决方案的开端,但它自己的考虑,自动生成的列仍然有属性名称作为标题。
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.
要获得显示名称,您需要添加一个程序(在$ C $落后三)处理GridAutoGeneratingColumn事件:
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
这是额外的,更好的解决方案是使用ComponentModel.DataAnnotations命名空间,并指定短名称:
An additional and better solution is to use the ComponentModel.DataAnnotations namespace and specify ShortName:
Public Class modelQ016
<Display(shortname:="DB Name")>
Public Property DBNAME As String
...
OnGeneratingColumn变为:
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
请注意,属性在属性排列的顺序有所不同,所以你必须使用,而不是一个数值参数的GetType(......)......如此有趣!
Note that the order of attributes in the attribute array changes, so you must use the GetType(...) instead of a numeric parameter... Such fun!