Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF databinding - set NotifyOnValidationError to true for all bindings with validation rules

Tags:

.net

binding

wpf

In my WPF application, I want to set NotifyOnValidationError to true (the framework defaults it to false) for all child controls/bindings if they have any ValidationRules attached to the binding. Indeed, it would be nice to specify other binding defaults too - e.g. ValidatesOnDataErrors should also always be true.

For example, in the following text box I don't want to have to manually specify the NotifyOnValidationError property.

<TextBox>
    <TextBox.Text>
        <Binding Path="PostalCode" 
                 ValidatesOnDataErrors="True" 
                 NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <rules:PostalCodeRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
like image 415
Reddog Avatar asked Feb 24 '11 00:02

Reddog


2 Answers

Following up on Ragepotato's answer.
The easiest way to do this is to create your own Binding that inherits from Binding and then set the things you need, like NotifyOnValidationError="True" and ValidatesOnDataErrors="True" in the constructor.

public class ExBinding : Binding
{
    public ExBinding()
    {
        NotifyOnValidationError = true;
        ValidatesOnDataErrors = true;
    }
}

And then you use this Binding instead

<TextBox>
    <TextBox.Text>
        <local:ExBinding Path="PostalCode">
            <local:ExBinding.ValidationRules>
                <rules:PostalCodeRule />
            </local:ExBinding.ValidationRules>
        </local:ExBinding>
    </TextBox.Text>
</TextBox>
like image 59
Fredrik Hedblad Avatar answered Nov 10 '22 08:11

Fredrik Hedblad


Since Binding is just a markup extension you could create a custom Markup Extensions that extends Binding and sets those properties to your desired defaults.

like image 5
Ragepotato Avatar answered Nov 10 '22 07:11

Ragepotato