我正在编写一个WPF应用程序,我想使用数据注释来指定像Required
字段、Range
等内容。
我的ViewModel类使用常规的INotifyPropertyChanged
接口,我可以很容易地使用C# 4 Validator
验证整个对象,但如果它们不能正确验证,我也想让这些字段变成红色。我在这里找到了这篇博客文章(http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/28/wpf-data-validation-using-net-data-annotations-part-ii.aspx),它讲述了如何编写您的基本视图模型以实现IDataErrorInfo
并简单地使用验证器,但是实现实际上无法编译,我也看不出它将如何工作。有问题的方法是:
/// <summary>
/// Validates current instance properties using Data Annotations.
/// </summary>
/// <param name="propertyName">This instance property to validate.</param>
/// <returns>Relevant error string on validation failure or <see cref="System.String.Empty"/> on validation success.</returns>
protected virtual string OnValidate(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentException("Invalid property name", propertyName);
}
string error = string.Empty;
var value = GetValue(propertyName);
var results = new List<ValidationResult>(1);
var result = Validator.TryValidateProperty(
value,
new ValidationContext(this, null, null)
{
MemberName = propertyName
},
results);
if (!result)
{
var validationResult = results.First();
error = validationResult.ErrorMessage;
}
return error;
}
问题在于没有提供
GetValue
。他可能在谈论继承DependencyObject
时所带来的GetValue
,但语法仍然无法正常工作(它期望您将DependencyProperty
作为参数传递),但我使用普通CLR属性,并在setter上调用了OnPropertyChanged("MyProperty")
。有没有好的方法将验证连接到
IDataErrorInfo
接口?