I have a text input area defined like this:
<TextBox>
<TextBox.Text>
<Binding Path="MyProperty">
<Binding.ValidationRules>
<valid:MyValidator/>
</Binding.ValidationRules>
开发者_C百科 </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?
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);
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.
精彩评论