本文介绍了清单在一个WPF控件的所有Validation.Errors?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到绑定一个单一的控制(如TextBlock的列表框或)列出一个WPF窗体上的所有验证错误的简单方法。大多数源代码示例我已经能够找到刚才绑定控件(Validation.Errors)[0] .ErrorContent仅显示一个验证错误。

I'm trying to find a simple way of binding a single control (eg. TextBlock or ListBox) to list all the validation errors on a WPF form. Most source code examples I have been able to find just bind a control to (Validation.Errors)[0].ErrorContent which only shows a single validation error.

我米目前使用有效性规则类的,虽然我开到使用IDataErrorInfo的,或者建立一个自定义的验证。我只是不知道如何来完成我所期望的是一个常见的用例。

I'm currently using ValidationRule classes, though I'm open to using IDataErrorInfo, or building a custom validator. I'm just not sure how to accomplish what I would expect to be a common use-case.

我如何列出一个控制所有验证错误一个WPF形式?

How do I list all validation errors in one control on a WPF form?

推荐答案

我不认为你可以像这样使用(Validation.Errors)任何约束力。其原因是,验证附加属性提供的一到一绑定控件和装饰器的网站之间的关系,所以你不能从不同的控制在一个装饰器结合验证错误 - 最后的人会永远接管网站。顺便说一句,我不知道为什么Validation.Errors是一个数组? - 也许从同一控制多个错误

I don't think you can do anything like this using (Validation.Errors) binding. The reason is that Validation attached property provides one-to-one relationship between a bound control and an adorner site, so you just cannot combine validation errors from different controls in one adorner - the last one would always "take over" the site. BTW, I have no idea why Validation.Errors is an array - maybe for multiple errors from the same control?

不过,还是有希望的 - 你必须至少在两方面为了解决这个问题,而无需使用验证装饰器

But there is still hope - you have at least two ways to solve this, without using validation adorners.

第一个是简单的钉子 - 如果你使用IDataErrorInfo的,你有一些机制检查你的对象有效性的约束值。然后,你可以写沿

The first one is simple as a nail - if you use IDataErrorInfo, you have some mechanism for checking the bound values of your object for validity. You could then write something along the lines of

public IEnumerable<string> CombinedErrors
{
    get { 
           if (FirstValError) yield return "First value error"; 
           if (SecondValError) yield return "Second value error"; 
        }
}

和绑定一些的ItemsControl到CombinedErrors属性。

and bind some ItemsControl to the CombinedErrors property

第二个将涉及设置NotifyOnValidationError = TRUE每个绑定(提高Validation.Error路由事件),并捕捉顶部容器上此事件:

The second one would involve setting NotifyOnValidationError=True on each binding (to raise Validation.Error routed event) and catch this event on the top container:

public List<ValidationError> MyErrors { get; private set; }

private void Window_Error(object sender, 
    System.Windows.Controls.ValidationErrorEventArgs e)
{
    if (e.Action == ValidationErrorEventAction.Added)
        MyErrors.Add(e.Error);
    else
        MyErrors.Remove(e.Error);
}



,那么你同样可以绑定这些对任何ItemsControl的。

then you can bind these similarly to any ItemsControl.

这篇关于清单在一个WPF控件的所有Validation.Errors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 10:32