Silverlight - INotifyDataErrorInfo和复杂的属性绑定

Ron*_*rby 5 .net validation silverlight

我有一个实现INotifyDataErrorInfo的视图模型.我正在将文本框绑定到其中一个视图模型属性,如下所示:

<TextBox Text="{Binding SelfAppraisal.DesiredGrowth, Mode=TwoWay, ValidatesOnNotifyDataErrors=True,NotifyOnValidationError=True}"  Height="200" 
                         TextWrapping="Wrap"/>
Run Code Online (Sandbox Code Playgroud)

数据绑定有效,但是当我添加如下验证错误时,UI没有响应:

// validation failed
foreach (var error in vf.Detail.Errors)
{
    AddError(SelfAppraisalPropertyName + "." + error.PropertyName, error.ErrorMessage);
}
Run Code Online (Sandbox Code Playgroud)

GetErrors("SelfAppraisal.DesiredGrowth")immidiate窗口中运行后,我可以看到: Count = 1
[0]: "Must be at least 500 characters. You typed 4 characters."

我已经确保添加错误时的连接与文本框中的绑定表达式匹配,但是UI在我切换到使用复杂类型之前不会显示消息.

我究竟做错了什么?使用INotifyDataErrorInfo进行验证是否支持此功能?

更新

我的viewmodel实现了INotifyDataErrorInfo,在添加/删除错误时会引发ErrorsChanged.

protected void RaiseErrorsChanged(string propertyName)
    {
        if (ErrorsChanged != null)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ed *_*pel 2

正在TextBox监视SelfAppraisal对象的错误通知。看来您正在使用SelfAppraisal property将错误添加到对象中。尝试将错误添加到SelfAppraisal对象中:

foreach (var error in vf.Detail.Errors)
{
    SelfAppraisal.AddError(error.PropertyName, error.ErrorMessage);
}
Run Code Online (Sandbox Code Playgroud)

这将引发该属性的实例上的事件SelfAppraisal。查找与该属性绑定的名称的TextBox错误。DesiredGrowth

也许它有助于说明TextBox不监视根对象是否存在属性名称为 的错误SelfAppraisal.DesiredGrowth

更新:使用 ViewModel 模式对您有利。在您的虚拟机上创建一个属性:

public string SelfAppraisalDesiredGrowth
{
    get { return SelfAppraisal != null ? SelfAppraisal.DesiredGrowth : null; }
    set
    {
        if (SelfAppraisal == null)
        {
            return;
        }

        if (SelfAppraisal.DesiredGrowth != value)
        {
            SelfAppraisal.DesiredGrowth = value;
            RaisePropertyChanged("SelfAppraisalDesiredGrowth");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

绑定到该属性:

<TextBox Text="{Binding SelfAppraisalDesiredGrowth, Mode=TwoWay, ValidatesOnNotifyDataErrors=True,NotifyOnValidationError=True}"  Height="200" TextWrapping="Wrap"/>
Run Code Online (Sandbox Code Playgroud)

验证时使用 VM 属性:

// validation failed
foreach (var error in vf.Detail.Errors)
{
    AddError(SelfAppraisalPropertyName + error.PropertyName, error.ErrorMessage);
}
Run Code Online (Sandbox Code Playgroud)