我有一个实现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")之后,我可以看到:Count = 1
[0]: "Must be at least 500 characters. You typed 4 characters."
我已经确保添加错误时的连接与textbox上的绑定表达式匹配,但UI不会像我切换到使用复杂类型之前那样显示消息。
我做错了什么?使用INotifyDataErrorInfo进行验证是否支持这一点?
更新
我的视图模型实现了INotifyDataErrorInfo,在添加/删除错误时确实会引发ErrorsChanged。
protected void RaiseErrorsChanged(string propertyName)
{
if (ErrorsChanged != null)
{
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}发布于 2011-06-21 03:39:33
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, Mode=TwoWay, ValidatesOnNotifyDataErrors=True,NotifyOnValidationError=True}" Height="200" TextWrapping="Wrap"/>验证时使用VM属性:
// validation failed
foreach (var error in vf.Detail.Errors)
{
AddError(SelfAppraisalPropertyName + error.PropertyName, error.ErrorMessage);
}https://stackoverflow.com/questions/6416206
复制相似问题