【问题标题】:Silverlight - INotifyDataErrorInfo and complex property bindingSilverlight - INotifyDataErrorInfo 和复杂的属性绑定
【发布时间】:2011-09-18 23:04:18
【问题描述】:

我有一个实现 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);
}

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

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

我做错了什么?使用 INotifyDataErrorInfo 进行验证是否支持这一点?

更新

实现 INotifyDataErrorInfo 的视图模型在添加/删除错误时确实会引发 ErrorsChanged。

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

【问题讨论】:

  • 你会引发 ErrorsChanged 事件吗?
  • 是的,即使在我的视图模型中添加/删除错误时,我也会提出这个问题。
  • 谢谢,支持这个的人。不必在这个对象上包装属性会非常酷。

标签: .net silverlight validation


【解决方案1】:

TextBox 正在监视 SelfAppraisal 对象以获取错误通知。您似乎正在使用SelfAppraisal property 将错误添加到对象中。尝试将错误添加到SelfAppraisal 对象:

foreach (var error in vf.Detail.Errors)
{
    SelfAppraisal.AddError(error.PropertyName, error.ErrorMessage);
}

这将在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");
        }
    }
}

绑定到这个属性:

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

【讨论】:

  • SelfAppraisal 没有实现 INotifyDataErrorInfo。我可以指示文本框查看事件的视图模型并仍然绑定到属性的属性吗?
猜你喜欢
  • 2010-10-16
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
相关资源
最近更新 更多