wpf - 如何正确实现 INotifyDataErrorInfo?

标签 wpf inotifydataerrorinfo

我有点困惑 MSDN example .

目前尚不清楚如何处理和设置实体相关错误。

示例代码:

public System.Collections.IEnumerable GetErrors(string propertyName)
{
    if (String.IsNullOrEmpty(propertyName) || 
        !errors.ContainsKey(propertyName)) return null;
    return errors[propertyName];
}

但是 GetErrors() 的文档指出:

propertyName - The name of the property to retrieve validation errors for; or null or Empty, to retrieve entity-level errors.



另一个例子建议只返回字典的 _errors.Values。这只是所有属性错误,但又不是实体错误。

最佳答案

根据文档中的“备注”部分:MSDN: INotifyDataErrorInfo Interface

This interface enables data entity classes to implement custom validation rules and expose validation results asynchronously. This interface also supports custom error objects, multiple errors per property, cross-property errors, and entity-level errors. Cross-property errors are errors that affect multiple properties. You can associate these errors with one or all of the affected properties, or you can treat them as entity-level errors. Entity-level errors are errors that either affect multiple properties or affect the entire entity without affecting a particular property.



我可能会建议执行 GetErrors高度依赖于您的错误处理方案。例如,如果您不打算支持 Entity-Level错误,那么您的示例代码就足够了。但是,如果您确实需要支持 Entity-Level错误,那么你可以处理 IsNullOrEmpty单独条件:
Public IEnumerable GetErrors(String propertyName)
{
    if (String.IsNullOrEmpty(propertyName))
        return entity_errors;
    if (!property_errors.ContainsKey(propertyName))
        return null;
    return property_errors[propertyName];
}

关于wpf - 如何正确实现 INotifyDataErrorInfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15874453/

相关文章:

c# - 检查文本框中输入的值是否为 WPF 中的双数

c# - 如何使用 INotifyDataErrorInfo 接口(interface)验证 Observable 集合

wpf - 为什么将 DependencyProperty 成员声明为 public 不 protected ?

c# - 转换器 - 我应该使用多少?使用 MVVM 在 WPF 中还有其他方法吗?

WPF TreeView 上下文菜单命令参数

c# - WPF 列表框数据验证

c# - 列表框中的 WPF 数据模板多态性

wpf - 如何添加验证以查看模型属性或如何实现 INotifyDataErrorInfo

c# - UWP INotifyDataErrorInfo