问题
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>
回答1:
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.
回答2:
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>
来源:https://stackoverflow.com/questions/5099064/wpf-databinding-set-notifyonvalidationerror-to-true-for-all-bindings-with-vali