Silverlight - INotifyDataErrorInfo和复杂的属性绑定

时间:2011-06-20 19:13:21

标签: .net silverlight validation

我有一个实现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."

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

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

更新

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

protected void RaiseErrorsChanged(string propertyName)
    {
        if (ErrorsChanged != null)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }
    }

1 个答案:

答案 0 :(得分:2)

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);
}