我去的选择是在被所有的ViewModels和实体扩展一个基类明确实现IDataErrorInfo的。这似乎是让事情与WPF结合在一起的最佳折衷办法,并且至少将调用者隐藏的IDataErrorInfo的实现保留为至少显得干净。我公开了一个受保护的ValidateProperty,如果需要,可以在子类中覆盖任何自定义行为(如Password/PasswordConfirmation方案)。
public abstract class DataErrorInfo : IDataErrorInfo
{
string IDataErrorInfo.Error
{
get { return null; }
}
string IDataErrorInfo.this[string columnName]
{
get { return ValidateProperty(columnName); }
}
protected virtual string ValidateProperty(string columnName)
{
// get cached property accessors
var propertyGetters = GetPropertyGetterLookups(GetType());
if (propertyGetters.ContainsKey(columnName))
{
// read value of given property
var value = propertyGetters[columnName](this);
// run validation
var results = new List<ValidationResult>();
var vc = new ValidationContext(this, null, null) { MemberName = columnName };
Validator.TryValidateProperty(value, vc, results);
// transpose results
var errors = Array.ConvertAll(results.ToArray(), o => o.ErrorMessage);
return string.Join(Environment.NewLine, errors);
}
return string.Empty;
}
private static readonly Dictionary<string, object> PropertyLookupCache =
new Dictionary<string, object>();
private static Dictionary<string, Func<object, object>> GetPropertyGetterLookups(Type objType)
{
var key = objType.FullName ?? "";
if (!PropertyLookupCache.ContainsKey(key))
{
var o = objType.GetProperties()
.Where(p => GetValidations(p).Length != 0)
.ToDictionary(p => p.Name, CreatePropertyGetter);
PropertyLookupCache[key] = o;
return o;
}
return (Dictionary<string, Func<object, object>>)PropertyLookupCache[key];
}
private static Func<object, object> CreatePropertyGetter(PropertyInfo propertyInfo)
{
var instanceParameter = Expression.Parameter(typeof(object), "instance");
var expression = Expression.Lambda<Func<object, object>>(
Expression.ConvertChecked(
Expression.MakeMemberAccess(
Expression.ConvertChecked(instanceParameter, propertyInfo.DeclaringType),
propertyInfo),
typeof(object)),
instanceParameter);
var compiledExpression = expression.Compile();
return compiledExpression;
}
private static ValidationAttribute[] GetValidations(PropertyInfo property)
{
return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
}
}
你是否在为你的实体使用poco类? – dnndeveloper 2010-10-02 21:30:11
我想问哪个是这个问题的原因,在这个解决方案中,我的实体必须扩展DataErrorInfo,但是否则它们会是POCO。 – TheCodeKing 2011-08-27 23:33:42