『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

public class Product {
 [Display(Name = "Product Number")][Range(0, 5000)] public int ProductID {
  get;
  set;
 }[Display(Name = "Name")][Required] public string ProductName {
  get;
  set;
 }[Display(Name = "Price")][DataType(DataType.Currency)] public double ListPrice {
  get;
  set;
 }[EnumDataType(typeof(ProductColor))] public ProductColor Color {
  get;
  set;
 }[Display(Name = "Available")] public bool InStock {
  get;
  set;
 }
 public Product() {}
 public Product(int _productID, string _productName, double _listPrice, ProductColor _color, bool _inStock) {
  this.ProductID = _productID;
  this.ProductName = _productName;
  this.ListPrice = _listPrice;
  this.Color = _color;
  this.InStock = _inStock;
 }
}
public enum ProductColor {
 Red,
 White,
 Purple,
 Blue
}

DataGrid Example - XAML

<Grid x:Name="LayoutRoot"> <ScrollViewer x:Name="PageScrollViewer"> <StackPanel x:Name="ContentStackPanel"> <TextBlock x:Name="HeaderText" Text="Products"/> <sdk:DataGrid x:Name="DataGrid1" Foreground="Black" AutoGenerateColumns="True"> </sdk:DataGrid> </StackPanel> </ScrollViewer> </Grid>

DataGrid Example - CS

public partial class ProductPage: Page {
 ObservableCollection < Product > AvailableProducts;
 public ProductPage() {
  InitializeComponent();
  AvailableProducts = new ObservableCollection < Product > ();
  AvailableProducts.Add(new Product(1, "Bike", 500, ProductColor.Red, true));
  AvailableProducts.Add(new Product(2, "Chair", 250, ProductColor.White, true));
  AvailableProducts.Add(new Product(3, "Plate", 20, ProductColor.Purple, false));
  AvailableProducts.Add(new Product(4, "Kite", 15, ProductColor.Blue, true));
  DataGrid1.ItemsSource = AvailableProducts;
 }
}

 

Data Binding Example - XAML

<!-- NOTE: By convention, the sdk prefix indicates a URI-based XAML namespace declaration for Silverlight SDK client libraries. This namespace declaration is valid for Silverlight 4 only. In Silverlight 3, you must use individual XAML namespace declarations for each CLR assembly and namespace combination outside the scope of the default Silverlight XAML namespace. For more information, see the help topic "Prefixes and Mappings for Silverlight Libraries". --> <UserControl x:Class="ValidationSample.MainPage" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"> <Grid x:Name="LayoutRoot" Margin="15" > <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="300"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="35"/> <RowDefinition Height="35"/> <RowDefinition Height="35"/> <RowDefinition Height="100"/> </Grid.RowDefinitions> <!-- Unbound Date of Birth field --> <sdk:Label Content="Date of Birth" IsRequired="True" Margin="5" /> <StackPanel Orientation="Horizontal" Grid.Column="1"> <sdk:DatePicker Height="23" /> <sdk:DescriptionViewer Description="Please enter your date of birth."/> </StackPanel> <!-- ID Number field --> <sdk:Label Grid.Row="1" Margin="5" Target="{Binding ElementName=tbIdNumber}" /> <StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="1"> <TextBox x:Name="tbIdNumber" Height="23" Width="100" Text="{Binding IdNumber, Mode=TwoWay,  ValidatesOnExceptions=true, NotifyOnValidationError=true}" /> <sdk:DescriptionViewer Target="{Binding ElementName=tbIdNumber}"/> </StackPanel> <!-- Name field --> <sdk:Label Grid.Row="2" Margin="5" Target="{Binding ElementName=spName}" PropertyPath="FirstName" /> <StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="2"> <StackPanel x:Name="spName" Orientation="Horizontal" > <TextBox x:Name="tbFirstName" Text="{Binding FirstName, Mode=TwoWay,  ValidatesOnExceptions=true, NotifyOnValidationError=true}"  Height="23" Width="100" /> <TextBox x:Name="tbLastName" Text="{Binding LastName, Mode=TwoWay,  ValidatesOnExceptions=true, NotifyOnValidationError=true}"  Height="23" Width="100" /> </StackPanel> <sdk:DescriptionViewer Target="{Binding ElementName=spName}" PropertyPath="FirstName"/> </StackPanel> <!-- ValidationSummary --> <sdk:ValidationSummary Grid.ColumnSpan="2" Grid.Row="3" /> </Grid> </UserControl>

 

 

 

Data Binding Example - CS
using System.ComponentModel.DataAnnotations;
using System.Windows.Controls;
namespace ValidationSample {
 public partial class MainPage: UserControl {
  public MainPage() {
   InitializeComponent();
   this.DataContext = new Customer("J", "Smith", 12345);
  }
 }
 public class Customer {
  // Private data members. 
  private int m_IdNumber;
  private string m_FirstName;
  private string m_LastName;
  public Customer(string firstName, string lastName, int id) {
    this.IdNumber = id;
    this.FirstName = firstName;
    this.LastName = lastName;
   }
   // Public properties. 
   [Display(Name = "ID Number", Description = "Enter an integer between 0 and 99999.")][Range(0, 99999)] public int IdNumber {
    get {
     return m_IdNumber;
    }
    set {
     Validator.ValidateProperty(value, new ValidationContext(this, null, null) {
      MemberName = "IdNumber"
     });
     m_IdNumber = value;
    }
   }[Display(Name = "Name", Description = "First Name + Last Name.")][Required(ErrorMessage = "First Name is required.")][RegularExpression(@ "^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Numbers and special characters are not allowed in the name.")] public string FirstName {
    get {
     return m_FirstName;
    }
    set {
     Validator.ValidateProperty(value, new ValidationContext(this, null, null) {
      MemberName = "FirstName"
     });
     m_FirstName = value;
    }
   }[Required(ErrorMessage = "Last Name is required.")][RegularExpression(@ "^[a-zA-Z''-'\s]{1,40}$", ErrorMessage = "Numbers and special characters are not allowed in the name.")][StringLength(8, MinimumLength = 3, ErrorMessage = "Last name must be between 3 and 8 characters long.")] public string LastName {
    get {
     return m_LastName;
    }
    set {
     Validator.ValidateProperty(value, new ValidationContext(this, null, null) {
      MemberName = "LastName"
     });
     m_LastName = value;
    }
   }
 }
}

 

转载于:https://my.oschina.net/skyler/blog/706184

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值