lokusking
lokusking

Reputation: 7456

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

In my program I have lots of Textboxes.

They are all bound via MVVM-Pattern.

Everything works nice. Now I want to implent some kind of Validation and have decided to use a mix of Validationrules AND! IDataErrorInfo. After testing this out a few times it all works well. But now I have a question.

I write my XAML-Code like

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

Lets say I have 40 TextBoxes in total. Do I always have to write

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

or can I set this to be some sort of default?

I do not want to create a derived TextBox because of three properties.

Upvotes: 0

Views: 67

Answers (1)

Martin Moser
Martin Moser

Reputation: 6267

First of all, Textbox.Text binds TwoWay by default, so no need to specify it here. For the other thing, the only idea that comes to my mind is to create a 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>

Upvotes: 1

Related Questions