Programmatically change validation rule in WPF TextBox

I have a text input area defined as follows:

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

My problem is that, depending on a different setting, what should be inserted here changes. Thus, the behavior of input validation must change.

How can I change the code of an active validation rule for a specific text field?

+7
wpf binding
source share
2 answers

Use BindingOperations.GetBinding () to get the Binding object for TextBox.Text. Then manipulate the ValidationRules collection as you like.

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

The most hacky solution that comes to mind is to define one text box for each of the validation rules that must be set. Associate one text box with each of the validation rules. Then, depending on the external parameter / condition, collapse / hide all text fields except those that should be applied to the validation rule.

+1
source share

All Articles