我正在尝试找到验证 MVVM 中数据的最佳方法。
目前,我正在尝试使用 MVVM 模式将 IDataErrorInfo 与数据注释结合使用。
然而,似乎没有任何作用,我不确定我可能做错了什么。我有这样的东西。
Model
public class Person : IDataErrorInfo
{
[Required(ErrorMessage="Please enter your name")]
public string Name { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
string IDataErrorInfo.this[string propertyName]
{
get
{
return OnValidate(propertyName);
}
}
protected virtual string OnValidate(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentException("Property may not be null or empty", propertyName);
string error = string.Empty;
var value = this.GetType().GetProperty(propertyName).GetValue(this, null);
var results = new List<ValidationResult>();
var context = new ValidationContext(this, null, null) { MemberName = propertyName };
var result = Validator.TryValidateProperty(value, context, results);
if(!result)
{
var validationResult = results.First();
error = validationResult.ErrorMessage;
}
return error;
}
}
模型代码由解决方案提供如何在 MVVM 中捕获 DataAnnotations 验证 https://stackoverflow.com/questions/13136814/how-to-catch-dataannotations-validation-in-mvvm (不幸的是,这个答案不符合我的标准。)
视图模型
public class PersonViewModel
{
private Person _person;
public string Name
{
get
{
return _person.Name
}
set
{
_person.Name = value;
}
}
}
View
<Label Content="Name:" />
<TextBox Text="{Binding UpdateSourceTrigger=LostFocus,
Path=Name,
ValidatesOnDataErrors=True,
NotifyOnValidationError=true}" />
有没有什么方法可以保持模型、视图和视图模型之间的分离,同时仍然利用数据注释通过 IDataErrorInfo 进行验证?