WPF databinding - set NotifyOnValidationError to true for all bindings with validation rules
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>
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>
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.
精彩评论