views:

1159

answers:

2

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?

+4  A: 

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);
itowlson
This seems to be exactly what I want, Ill try it out and come back to accept your answer. :)
mizipzor
A: 

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.

mizipzor