『WPF』使用 [Annotation] 註釋來定製數據/實體類

幾點說明express

  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應該不會成爲何難事的,關鍵仍是看這二者官方的意思了~

正文app

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.ide

  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.ui

  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.DataAnnotationsthis

  1. 命名空間:System.ComponentModel.DataAnnotations
  2. 顯示屬性是在DataGrid控件中自動應用的。
  3. 當數據被控件(如:Label,DescriptionViewer)綁定,你能夠手動的檢索顯示屬性的值。

image

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

 

DataGrid Example - CSspa

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 - XAMLcode

<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 - CScomponent

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 - XAMLorm

<!-- 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;
    }
   }
 }
}
相關文章
相關標籤/搜索