『WPF』使用 [Annotation] 注释来定制数据/实体类

几点说明

  1. 主要内容来自「MSDN」Using Data Annotations to Customize Data Classes
  2. 注意,DataAnnotations 好像是需要到 VS2008 SP1之后才会有,至少我的VS2010 SP1有,我的VS2008没有~
  3. 使用Annotations注释一个数据类,比我想象中的要简单很多
    1. 首先是在要进行注释的实体类中,引入DataAnnotations命名空间
    2. 其次是要使用[Display(Name="", ...)]这样的注释,加在属性的前面(这个貌似是要加到Public类型的属性前面)
    3. 然后就可以在DataGrid中直接看到效果了~
  4. 相对于Java中,方便的使用Annotation来配置Hibernate与Spring,我想,在.NET中使用Annotation来配置NHibernate与Spring.NET应该不会成为什么难事的,关键还是看这两者官方的意思了~

正文

When you use data classes (also known as entity classes) in your Silverlight application, you can apply attributes to the class or members that specify validation rules, specify how the data is displayed, and set relationships between classes. The System.ComponentModel.DataAnnotations namespace contains the classes that are used as data attributes. By applying these attributes on the data class or member, you centralize the data definition and do not have to re-apply the same rules in multiple places.

  1. 当你在Silverlight应用程序中使用数据类(或者实体类),你能够应用属性到类或成员,以指定验证规则、数据显示方式、类之间的关系。
  2. System.ComponentModel.DataAnnotations 命名空间包含被当成是数据属性的类。
  3. 通过在数据类或成员上应用这些属性,你可以集中的定义它们的属性,而不用多次的去定义。

image

All validation attributes derive from the ValidationAttribute class. The logic to determine if a value is valid is implemented in the overridden IsValid method. The Validate method calls the IsValid method and throws a ValidationException if the value is not valid.

  1. 命名空间:System.ComponentModel.DataAnnotations
  2. 所有的验证属性都来自ValidationAttribute 类。
  3. 验证逻辑的实现需要重写IsValid方法。
  4. 如果验证不通过,则Validate方法调用IsValid方法以及抛出一个ValidationException异常。

image

The display attributes are automatically applied when used with the DataGrid control. You can manually retrieve display attribute values when data binding by using controls such as Label and DescriptionViewer. 命名空间:System.ComponentModel.DataAnnotations

  1. 命名空间:System.ComponentModel.DataAnnotations
  2. 显示属性是在DataGrid控件中自动应用的。
  3. 当数据被控件(如:Label,DescriptionViewer)绑定,你可以手动的检索显示属性的值。

image

  1. 命名空间:System.ComponentModel.DataAnnotations

DataGrid Example - CS

DataGrid Example - XAML

DataGrid Example - CS

Data Binding Example - XAML

Data Binding Example - CS

posted @ 2012-02-20 10:52  莫不逢  阅读(1767)  评论(0编辑  收藏  举报