WPF ValidationRule Confirmation when loading a control

I have control with this check

<MyPicker.SelectedItem> <Binding Path="Person.Value" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True"> <Binding.ValidationRules> <rules:MyValidationRule ValidationType="notnull"/> </Binding.ValidationRules> </Binding> </MyPicker.SelectedItem> 

This is the validation class:

 class MyValidationRule : ValidationRule { private string _validationType; public string ValidationType { get { return _validationType; } set { _validationType = value; } } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { ValidationResult trueResult = new ValidationResult(true, null); switch (_validationType.ToLower()) { case "notnull": return value == null ? new ValidationResult(false, "EMPTY FIELD") : trueResult; default: return trueResult; } } } 

Question: When a property is changed, the Validate () method is called, which is the correct one.

But to call this method at the very beginning when creating MyControl ? I need to prove immediate after initialization if there is a null value in the control (and display a validation error)

+7
validation wpf
source share
2 answers

OK I decided: You are forcibly checking when an element is associated with a simple property - ValidatesOnTargetUpdated :

  <rules:MyValidationRule ValidatesOnTargetUpdated="True" ValidationType="notnull"/> 
+16
source share

Your answer is great ... I just want to say that.

I have so many controls to check and so many rules, so I created a constructor in my validationRule class and set ValidatesOnTargetUpdated to True there.

This way, I don’t have to go through all my pages and controls to add this property to the validation rule.

subscription base

 public class MyRule : ValidationRule { public MyRule() : base() { ValidatesOnTargetUpdated = true; } ... } public class MyRule2 : MyRule { public MyRule2() : base() { } ... } 
+1
source share

All Articles