Programmatically change validation rule in WPF TextBox

徘徊边缘 提交于 2019-12-21 09:07:56

问题


I have a text input area defined like this:

    <TextBox>
        <TextBox.Text>
            <Binding Path="MyProperty">
                <Binding.ValidationRules>
                    <valid:MyValidator/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

My problem is that, depending on another setting, what is supposed to be inserted here varies. And thus, the validation behavior of the input data should change.

How can I in the code behind change the active validation rule for a certain textbox?


回答1:


Use BindingOperations.GetBinding() to get the Binding object for the TextBox.Text. Then manipulate the binding's ValidationRules collection as you see fit.

Binding binding = BindingOperations.GetBinding(myTextBox, TextBox.TextProperty);
binding.ValidationRules.Clear();
binding.ValidationRules.Add(myCrazyValidationRule);



回答2:


The most hacky solution that comes to mind is to define one textbox for each of the validation rules that should be able to be set. Bind one textbox to each of the validation rules. Then, depending on the external setting/condition, collapse/hide all the textboxes except the one with the validation rule that should be applied.



来源:https://stackoverflow.com/questions/1592919/programmatically-change-validation-rule-in-wpf-textbox

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