Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change validation rule in WPF TextBox

Tags:

binding

wpf

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?

like image 478
Mizipzor Avatar asked Oct 20 '09 07:10

Mizipzor


2 Answers

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);
like image 105
itowlson Avatar answered Nov 01 '22 12:11

itowlson


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.

like image 27
Mizipzor Avatar answered Nov 01 '22 11:11

Mizipzor