如何正确实现INotifyDataErrorInfo?

4

我对MSDN示例有些困惑。

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

示例中的代码:

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

但是对于GetErrors()的文档说明如下: propertyName - 要检索验证错误的属性名称; 或者为null或Empty,以检索实体级别的错误。
另一个例子建议只返回字典的_errors.Values。这仅涵盖所有的属性错误,但不包括实体错误。

1
“Entity-Level”似乎是一个术语,用于描述“通用”的错误(与特定属性无关)。此错误可能与许多或所有属性有关,也可能与没有特定属性有关(可能是内部状态损坏)。 - Bradford Fisher
如何为视图模型属性添加验证或实现INotifyDataErrorInfo - user21970328
2个回答

2
根据文档中的“Remarks”部分所述:MSDN:INotifyDataErrorInfo接口 此接口允许数据实体类实现自定义验证规则,并异步公开验证结果。该接口还支持自定义错误对象、每个属性的多个错误、跨属性错误和实体级别错误。跨属性错误是指影响多个属性的错误。您可以将这些错误与所有受影响的属性之一或全部关联,也可以将它们视为实体级别错误。实体级别错误是指既影响多个属性又不影响特定属性的错误。
我建议根据您的错误处理方案来高度依赖于GetErrors的实现。例如,如果您不打算支持实体级别错误,则您的示例代码就足够了。但是,如果您确实需要支持实体级别错误,则可以单独处理IsNullOrEmpty条件。
Public IEnumerable GetErrors(String propertyName)
{
    if (String.IsNullOrEmpty(propertyName))
        return entity_errors;
    if (!property_errors.ContainsKey(propertyName))
        return null;
    return property_errors[propertyName];
}

1
由于我在这里没有找到合适的答案,所以我的解决方案是:当值为null或空时,返回所有验证错误。
private ConcurrentDictionary<string, List<ValidationResult>> modelErrors = new ConcurrentDictionary<string, List<ValidationResult>>();

public bool HasErrors { get => modelErrors.Any(); }

public IEnumerable GetErrors(string propertyName)
{
    if (string.IsNullOrEmpty(propertyName))
    {
        return modelErrors.Values.SelectMany(x => x);   // return all errors
    }
    modelErrors.TryGetValue(propertyName, out var propertyErrors);
    return propertyErrors;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接