为什么 DataAnnotations使用带有 AutoGenerateColumns=“True” 的 DataGrid 时被忽略
我正在使用 WPF DataGrid 绑定到自定义类的集合。在网格 XAML 中使用 AutoGenerateColumns="True",可以很好地创建和填充网格,但正如人们所期望的那样,标题是属性名称。
我尝试
<Display(Name:="My Name")>
从 System.ComponentModel.DataAnnotations 命名空间指定,但这没有效果。我还尝试
<DisplayName("My Name")>
从 System.ComponentModel 命名空间,但标题仍然不受影响。
是否无法使用 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.
I tried specifying
<Display(Name:="My Name")>
from the System.ComponentModel.DataAnnotations namespace and that has no effect. I also tried
<DisplayName("My Name")>
from the System.ComponentModel name space but still the headings are not affected.
Is there no way to specify column headings with the AutoGenerateColumns option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用@Marc的建议是解决方案的开始,但就其本身而言,自动生成的列仍然将属性名称作为标题。
要获取 DisplayName,您需要添加一个例程(在后面的代码中)来处理 GridAutoGenerateColumn 事件:
另一个更好的解决方案是使用 ComponentModel.DataAnnotations 命名空间并指定 ShortName:
OnGenerateColumn 变为:
请注意,属性中的顺序属性数组发生变化,因此您必须使用 GetType(...) 而不是数字参数...真有趣!
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:
An additional and better solution is to use the ComponentModel.DataAnnotations namespace and specify ShortName:
OnGeneratingColumn becomes:
Note that the order of attributes in the attribute array changes, so you must use the GetType(...) instead of a numeric parameter... Such fun!
您可以尝试旧的
System.ComponentModel.DisplayNameAttribute
。用 C# 语言来说,
[DisplayName("My Name")]
。特别是,这适用于PropertyDescriptor
,它支持大量数据绑定。You might try the older
System.ComponentModel.DisplayNameAttribute
. In C# parlance,[DisplayName("My Name")]
. In particular, this works withPropertyDescriptor
, which underpins a lot of data-binding.通过使用 @GilShalit 帖子,如果您此时在 C# 中使用资源(您可能应该支持多文化语言支持),则需要添加以下内容
带有注释的属性声明
<事件处理程序
By using @GilShalit post upon, this is what is needed to add in case that you are using Resources (as you probably should for multi culture language support) in C# in this time
Your property Declaration with Annotation
Event handler