C#学习教程:PrismIDataErrorInfovalidation在ViewModel实体上使用DataAnnotation我在绑定到表示层的ViewModel中使用干净的数据实体。我在基本ViewModel类中有一个IDataErrorInfo的通用实现,它对我的??实体(在本例中为用户)的DataAnnotation属性运行验证。问题是当绑定到一个实体时,WPF框架会在实体上查找IDataErrorInfo而不是ViewModel,这是我希望此逻辑所在的位置。如果我用我的ViewModel中的属性包装我的实体,那么一切正常,但我不想妥协使用ViewModel中的实体。有没有办法告诉WPF在ViewModel中查找IDataErrorInfo而不是绑定的子对象?谢谢,Mike我选择的选项是在所有ViewModel和实体扩展的基类中显式实现IDataErrorInfo。这似乎是解决WPF问题的最佳折衷方案,并且至少向调用者隐藏了IDataErrorInfo的实现,因此它们至少看起来很干净。我公开了一个受保护的ValidateProperty,如果需要,可以在子类中覆盖任何自定义行为(例如密码/密码确认场景)。公共抽象类DataErrorInfo:IDataErrorInfo{stringIDataErrorInfo.Error{get{returnnull;}}stringIDataErrorInfo.this[stringcolumnName]{get{returnValidateProperty(columnName);}}}protectedvirtualstringValidateProperty(stringcolumnName){//获取缓存的属性访问器varpropertyGetters=GetPropertyGetterLookups(GetType());if(propertyGetters.ContainsKey(columnName)){//读取给定属性的值varvalue=propertyGetters[columnName](this);//运行验证varresults=newList();varvc=newValidationContext(this,null,null){MemberName=columnName};Validator.TryValidateProperty(值,vc,结果);//转置结果varerrors=Array.ConvertAll(results.ToArray(),o=>o.ErrorMessage);返回string.Join(Environment.NewLine,errors);}返回字符串。空;}privatestaticreadonlyDictionaryPropertyLookupCache=newDictionary();私人静态词典>GetPropertyGetterLookups(类型对象类型){varkey=objType.FullName??"";如果(!PropertyLookupCache.ContainsKey(key)){varo=objType.GetProperties().Where(p=>GetValidations(p).Length!=0)。ToDictionary(p=>p.Name,CreatePropertyGetter);PropertyLookupCache[键]=o;返回o;}return(Dictionary>)PropertyLookupCache[key];}privatestaticFuncCreatePropertyGetter(PropertyInfopropertyInfo){varinstanceParameter=Expression.Parameter(typeof(object),"instance");varexpression=Expression.Lambda>(Expression.ConvertChecked(Expression.MakeMemberAccess(Expression.ConvertChecked(instanceParameter,propertyInfo.DeclaringType),propertyInfo),typeof(object)),instanceParameter);varcompiledExpression=expression.Compile();返回编译表达式;}privatestaticValidationAttribute[]GetValidations(PropertyInfoproperty){return(ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute),true);}}当然,我不知道你的整个场景,但我相信用ViewModel包装你的业务实体(或模型)是MVVM模式的重要组成部分,特别是如果您没有可绑定模型(您可以直接绑定到的模型)包装器可以在这种情况下包含错误管理信息或其他内容,例如自定义模型显示等。也就是说,您可以查看Prism的v4.0MVVMRI,它使用INotifyDataErrorInfo进行验证,并且应该提供对验证方法的有趣见解。我希望这有帮助。谢谢你,达米安。以上是C#学习教程:PrismIDataErrorInfovalidationusingDataAnnotationontheViewModelentity。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——本文来自网络收集,不代表立场,如涉及侵权,请点击有权联系管理员删除。如需转载请注明出处:
