实现方式:使用IDataErrorInfo接口实现验证。
public class Person : INotifyPropertyChanged, IDataErrorInfo
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
RaisePropertyChanged("Name");
}
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
if (_age != value)
{
_age = value;
RaisePropertyChanged("Age");
}
}
}
public string Error
{
get { return ""; }
}
public string this[string columnName]
{
get
{
if (columnName == "Age")
{
if (_age < 18)
{
return "年龄必须在18岁以上。";
}
}
return string.Empty;
}
}
public event PropertyChangedEventHandler PropertyChanged;
internal virtual void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
改造下上面的 Person 类,加上 [Range] ValidationAttribute:(需要添加 System.ComponentModel.DataAnnotations.dll)
[Range(19, 99, ErrorMessage="年龄必须在18岁以上。")]
public int Age
{
get { return _age; }
set
{
if (_age != value)
{
_age = value;
RaisePropertyChanged("Age");
}
}
}
public string this[string columnName]
{
get
{
var vc = new ValidationContext(this, null, null);
vc.MemberName = columnName;
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(this.GetType().GetProperty(columnName).GetValue(this, null), vc, res);
if (res.Count > 0)
{
return string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
}
return string.Empty;
}
}
(1) 自定义 ValidationAttribute
添加了一个针对上面 Person 的 Name 属性是否存在的校验:
class NameExists : ValidationAttribute
{
public override bool IsValid(object value)
{
var name = value as string;
// 这里可以到数据库等存储容器中检索
if (name != "Felix")
{
return false;
}
return true;
}
public override string FormatErrorMessage(string name)
{
return "请输入存在的用户名。";
}
}
[NameExists]
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
RaisePropertyChanged("Name");
}
}
}
(2) 利用 CustomerValidationAttribute