I am writing a WPF application and I want to use Data Annotations to indicate things like RequiredFields, Rangeetc.
My ViewModel classes use the normal interface INotifyPropertyChanged, and I can easily check the entire object using C # 4 Validator, but I would also like the fields to highlight red if they are not checked correctly. I found this blog post here (http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/28/wpf-data-validation-using-net-data-annotations-part-ii. aspx), which talks about how to write a base view model for an implementation IDataErrorInfoand just use Validator, but the implementation doesn’t actually compile, and I don’t see how it will work. This method is as follows:
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 . GetValue, , DependencyObject, ( , DependencyProperty ), CLR OnPropertyChanged("MyProperty"), .
IDataErrorInfo?