我可以将某些验证设置为 TextBox 实例的默认设置吗?

Can I set some validation to be a default setting on a TextBox instance?

在我的程序中我有很多文本框。

它们都是通过 MVVM-Pattern 绑定的。

一切正常。现在我想实施某种验证,并决定混合使用 Validationrules AND! IDataErrorInfo。 经过几次测试后,一切正常。 但是现在我有一个问题。

我写我的XAML-代码像

<TextBox Style="{StaticResource TextBoxStyle}" Width="150" >
    <TextBox.Text>
        <Binding Path="Name" Mode="TwoWay" ValidatesOnDataErrors="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged" />
    </TextBox.Text>
</TextBox>

假设我总共有 40 个文本框。我总是要写

Mode="TwoWay" ValidatesOnDataErrors="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged"

或者我可以将其设置为某种默认值吗?

由于三个属性,我不想创建派生的 TextBox。

首先,Textbox.Text默认绑定TwoWay,这里不用指定。另一方面,我想到的唯一想法是创建一个 CustomBinding。

    public class MyBinding : Binding
{
    public MyBinding()
        :base()
    {
        this.Mode = BindingMode.TwoWay;
        this.ValidatesOnDataErrors = true;
        this.ValidatesOnExceptions = true;
        this.UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
    }

    public MyBinding(string path) 
        : base(path)
    {
        this.Mode = BindingMode.TwoWay;
        this.ValidatesOnDataErrors = true;
        this.ValidatesOnExceptions = true;
        this.UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
    }
}


<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox x:Name="txt">
        <TextBox.Text>
            <local:MyBinding Path="Value" />
        </TextBox.Text>
    </TextBox>
</Grid>