我有一个实现INotifyDataErrorInfo的视图模型.我正在将文本框绑定到其中一个视图模型属性,如下所示:
<TextBox Text="{Binding SelfAppraisal.DesiredGrowth,Mode=TwoWay,ValidatesOnNotifyDataErrors=True,NotifyOnValidationError=True}" Height="200" TextWrapping="Wrap"/>
数据绑定有效,但是当我添加如下验证错误时,UI没有响应:
// validation failed foreach (var error in vf.Detail.Errors) { AddError(SelfAppraisalPropertyName + "." + error.PropertyName,error.ErrorMessage); }
在immidiate窗口中运行GetErrors(“SelfAppraisal.DesiredGrowth”)后,我可以看到:
计数= 1
[0]:“必须至少500个字符.您输入4个字符.”
我已经确保添加错误时的连接与文本框中的绑定表达式匹配,但是UI在我切换到使用复杂类型之前不会显示消息.
我究竟做错了什么?使用INotifyDataErrorInfo进行验证是否支持此功能?
更新
我的viewmodel实现了INotifyDataErrorInfo,在添加/删除错误时会引发ErrorsChanged.
protected void RaiseErrorsChanged(string propertyName) { if (ErrorsChanged != null) { ErrorsChanged(this,new DataErrorsChangedEventArgs(propertyName)); } }
解决方法
TextBox正在观察SelfAppraisal对象以获取错误通知.您似乎正在使用SelfAppraisal属性将错误添加到对象.尝试将错误添加到SelfAppraisal对象:
foreach (var error in vf.Detail.Errors) { SelfAppraisal.AddError(error.PropertyName,error.ErrorMessage); }
这将在SelfAppraisal属性的实例上引发事件. TextBox查找带有DesiredGrowth名称的错误,因为它绑定到该属性.
也许有必要说明TextBox没有在属性名称为SelfAppraisal.DesiredGrowth的错误中查看根对象.
更新:使用ViewModel模式为您带来好处.在VM上创建属性:
public string SelfAppraisalDesiredGrowth { get { return SelfAppraisal != null ? SelfAppraisal.DesiredGrowth : null; } set { if (SelfAppraisal == null) { return; } if (SelfAppraisal.DesiredGrowth != value) { SelfAppraisal.DesiredGrowth = value; RaisePropertyChanged("SelfAppraisalDesiredGrowth"); } } }
绑定到这个属性:
<TextBox Text="{Binding SelfAppraisalDesiredGrowth,NotifyOnValidationError=True}" Height="200" TextWrapping="Wrap"/>
验证时使用VM属性:
// validation failed foreach (var error in vf.Detail.Errors) { AddError(SelfAppraisalPropertyName + error.PropertyName,error.ErrorMessage); }