使用单个TextBlock显示错误消息?

时间:2014-05-14 13:48:25

标签: c# wpf validation

我的想法是,我想在窗口底部显示一个错误,但错误的来源可能是几个元素,如TextBoxes。

我已成功创建了单个字段的验证,但我很难实现我的新目标。

基于互联网教程,我创建了ValidationRule,它只检查输入的文本是否为空。然后添加了ErrorConverter:IValueConverter,将错误转换为字符串。在XAML部分,我有一个绑定到2个TextBoxes

的验证规则
<TextBox.Text>
    <Binding ElementName="Self" Path="MyProperty" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
        <Binding.ValidationRules>
            <local:ValidateEmpty />
        </Binding.ValidationRules>
    </Binding>
</TextBox.Text>

和一个用于显示错误的TextBox

Text="{Binding ElementName=myElement,
      Path=(Validation.Errors).CurrentItem,
      Converter={StaticResource ErrorConverter}

我拥有所有必需的DependencyProperties。问题是,错误文本框一次只能绑定到一个组件(在我的示例中为myElement),如果我将ElementName更改为我的网格名称或其他任何内容,没有任何反应,没有错误消息显示。

那么我应该怎样做才能“捕获”来自多个组件的错误?

1 个答案:

答案 0 :(得分:1)

我建议采用两种不同的方法:

第一种方式:ViewModel端验证

如果您的ViewModel实施IDataErrorInfo来定义输入中的错误,那么您的班级必须有string Error。 这个字符串实际上就是您要查找的确切事项:为多个错误提供单一理由。

这是我实施它的方式:

    public string Error
    {
        get { return PerformValidation(string.Empty); }
    }

    public virtual string this[string propertyName]
    {
        get
        {
            return PerformValidation(propertyName);
        }
    }

我的PerformValidation方法是虚拟的,要在继承类中重写。但这就是它的样子:

    protected override void PerformValidation(string propertyName = null)
    {

        if (string.IsNullOrEmpty(propertyName) || propertyName == "Property1")
        { }
        else if (string.IsNullOrEmpty(propertyName) || propertyName == "Property2")
        { }
        //...
    }

然后,我的TextBlock只绑定到Error字符串,该字符串将始终显示第一个遇到的错误

第二种方式:UI-ValidationRule方

或者,您只需使用MultiBinding,或只使用包含TextBlockRun对象的 <TextBlock TextAlignment="Center"> <Run Text="{Binding ElementName=myElement, Path=(Validation.Errors).CurrentItem, Converter={StaticResource ErrorConverter}}" /> <Run Text="{Binding ElementName=myElement2, Path=(Validation.Errors).CurrentItem, Converter={StaticResource ErrorConverter}}" /> <Run Text="{Binding ElementName=myElement3, Path=(Validation.Errors).CurrentItem, Converter={StaticResource ErrorConverter}}" /> </TextBlock> 即可。 简单的例子:

Run

每个元素只需添加一个{{1}}

相关问题