如果使用WCF RIA Service的话,Validation数据验证就很容易了,只需要在MetaData上作标记就可以了。项目添加域服务类后,会添加下面的元数据文件:

编辑里面的实体对象,添加验证条件:
public partial class Employee
{
// 通过此类可将自定义特性附加到
//Employee 类的属性。
//
// 例如,下面的代码将 Xyz 属性标记为
//必需属性并指定有效值的格式:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class EmployeeMetadata
{
// 元数据类不会实例化。
private EmployeeMetadata()
{
}
public DateTime BirthDate { get; set; }
public int ContactID { get; set; }
public bool CurrentFlag { get; set; }
public EntityCollection<Employee> Employee1 { get; set; }
public Employee Employee2 { get; set; }
public int EmployeeID { get; set; }
[StringLength(1)]
public string Gender { get; set; }
public DateTime HireDate { get; set; }
public string LoginID { get; set; }
public Nullable<int> ManagerID { get; set; }
public string MaritalStatus { get; set; }
public DateTime ModifiedDate { get; set; }
public string NationalIDNumber { get; set; }
public Guid rowguid { get; set; }
public bool SalariedFlag { get; set; }
public short SickLeaveHours { get; set; }
public string Title { get; set; }
public short VacationHours { get; set; }
}
}
Xaml绑定后就可以了,就自动实现了Validation,少去了很多编码工作,这其实是WCF RIA Service的自动代码生成代替我们做了。
<Grid x:Name="LayoutRoot" Background="White" Width="200">
<StackPanel>
<TextBox Text="{Binding EmployeeID,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True}" Margin="4"/>
<TextBox Text="{Binding Gender,Mode=TwoWay}" Margin="4"/>
</StackPanel>
</Grid>
.cs
public MainPage()
{
InitializeComponent();
this.DataContext = new Employee();
}
测试如图:
