几点说明
- 主要内容来自「MSDN」Using Data Annotations to Customize Data Classes
- 注意,DataAnnotations 好像是需要到 VS2008 SP1之后才会有,至少我的VS2010 SP1有,我的VS2008没有~
- 使用Annotations注释一个数据类,比我想象中的要简单很多
- 首先是在要进行注释的实体类中,引入DataAnnotations命名空间
- 其次是要使用[Display(Name="", ...)]这样的注释,加在属性的前面(这个貌似是要加到Public类型的属性前面)
- 然后就可以在DataGrid中直接看到效果了~
- 相对于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.
- 当你在Silverlight应用程序中使用数据类(或者实体类),你能够应用属性到类或成员,以指定验证规则、数据显示方式、类之间的关系。
- System.ComponentModel.DataAnnotations 命名空间包含被当成是数据属性的类。
- 通过在数据类或成员上应用这些属性,你可以集中的定义它们的属性,而不用多次的去定义。
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.
- 命名空间:System.ComponentModel.DataAnnotations
- 所有的验证属性都来自ValidationAttribute 类。
- 验证逻辑的实现需要重写IsValid方法。
- 如果验证不通过,则Validate方法调用IsValid方法以及抛出一个ValidationException异常。
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
- 命名空间:System.ComponentModel.DataAnnotations
- 显示属性是在DataGrid控件中自动应用的。
- 当数据被控件(如:Label,DescriptionViewer)绑定,你可以手动的检索显示属性的值。
- 命名空间:System.ComponentModel.DataAnnotations
DataGrid Example - CSpublic 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 - CSpublic 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 - CSusing 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;
}
}
}
}