{S0的}介绍
本文提出了一种方法来验证数据,这些数据显示在CodePlex上WPF Toolkit的DataGrid控件({A})。完成使用的IDataError的接口和在工程验证。NET框架3.5及以上。
背景
最近,我不得不来验证一个网格控件中的数据。我不想购买第三方组件,但决定使用WPF Toolkit的DataGrid的。看完优秀的文章,从科林・埃伯哈特({A2的})
我意识到了一些问题时使用。NET Framework 3.5中特别是当数据不能由用户修改,但补充编程。
我不得不实现一个小工具,它可以通过提取Zip文件部署。正因为如此,我不希望用户需要安装NET Framework 4.0中。不仅要解决我的验证问题。
最后,我做了如下所述的数据验证与。NET Framework 3.5中。使用代码
应用程序使用MVVM模式。如果你还没有听说这件事,我建议你读的好文章乔什 - 史密斯(A3的)。
验证发生的类被称为LT; PersonVMgt;这个类包含以下属性:字符串名字字符串姓氏:布尔HasJob(表示如果这个人有工作或工作)字符串职位名称
应当验证两件事情:第一个名字和姓氏应该只包含一个-ZA-Z字符和空格。它不应该允许一个人有HasJob的标志设置,但JOBNAME空,反之亦然。
第一条规则可以检查验证每个名称的属性。要检查的第二条规则,它不仅足以验证一个单一的财产,但多个属性。这个验证需要对整个Person对象的地方。
验证实施以下PersonVM索引(所需的LT; IDataErrorgt;接口):public string this[string columnName]
{
get
{
// apply property level validation rules
if (columnName == "FirstName")
{
if (String.IsNullOrEmpty(this.FirstName))
return "First Name needs to be filled";
if (!MyNameEx.Match(this.FirstName).Success)
return "First Name may only contain characters or spaces";
}
if (columnName == "LastName")
{
if (String.IsNullOrEmpty(this.LastName))
return "Last Name needs to be filled";
if (!MyNameEx.Match(this.LastName).Success)
return "Last Name may only contain characters or spaces";
}
// Method ValidateJob applies object level validation. In this example the consistency
// of the properties HasJob and JobName is checked on object level. An error is
// announced for JobName only. Otherwise the red error border would be presented for
// the JobName and the HasJob field and the error correction would be inconvenient
// for the user - try it out by uncommenting following line
// if (columnName == "JobName" || columnName == "HasJob")
if (columnName == "JobName")
{
return ValidateJob();
}
return "";
}
}
private string ValidateJob()
{
if (!this.HasJob && !String.IsNullOrEmpty(this.JobName))
{
return "Job Name is given, but Job Flag is not set!";
}
if (this.HasJob && String.IsNullOrEmpty(this.JobName))
{
return "Job Name is not given, but Job Flag is set!";
}
return "";
}
第二的IDataError的方法不写为PersonVM单独可以到基地或辅助类。{C}
多个字段的验证需要宣布一个领域 - JOBNAME - 在我的例子中,因为用户不能编辑多个领域一步纠正多领域的错误。出于这个原因,它是必要的模拟,JOBNAME已被更改时更新的HasJob复选框。这个通知是在HasJob二传手:public Boolean HasJob
{
get
{
return myHasJob;
}
set
{
myHasJob = value;
NotifyPropertyChanged("JobName");
NotifyErrorChanged();
}
}
相应的XAML代码的DataGrid显示如下:{体C3}
玩得开心!
历史2011年10月23日:第一次修订。2011年11月5日:更正对象级别的验证。|弗兰克・奥古斯丁