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

对着背影说爱祢 提交于 2020-01-01 09:23:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!