【发布时间】:2014-04-17 04:40:03
【问题描述】:
我正在尝试寻找在 MVVM 中验证数据的最佳方法。 目前,我正在尝试使用 MVVM 模式将 IDataErrorInfo 与数据注释一起使用。
但是,似乎没有任何效果,我不确定我做错了什么。我有这样的东西。
型号
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;
}
}
模型代码由How to catch DataAnnotations Validation in MVVM 的解决方案提供(很遗憾,这个答案不符合我的标准。)
视图模型
public class PersonViewModel
{
private Person _person;
public string Name
{
get
{
return _person.Name
}
set
{
_person.Name = value;
}
}
}
查看
<Label Content="Name:" />
<TextBox Text="{Binding UpdateSourceTrigger=LostFocus,
Path=Name,
ValidatesOnDataErrors=True,
NotifyOnValidationError=true}" />
有什么方法可以保持模型、视图和视图模型之间的分离,同时仍然使用数据注释进行 IDataErrorInfo 验证?
【问题讨论】:
标签: c# wpf validation mvvm data-annotations