Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ValidationRule Validate when the control is loaded

Tags:

validation

wpf

I have a control with this validation

<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 the property is changed, then the Validate( ) method is called which is correct.

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

like image 248
theSpyCry Avatar asked Apr 15 '10 09:04

theSpyCry


2 Answers

OK I've solved it: You force the validation when the element got bound with a simple property - ValidatesOnTargetUpdated:

 <rules:MyValidationRule ValidatesOnTargetUpdated="True"  ValidationType="notnull"/>
like image 96
theSpyCry Avatar answered Nov 15 '22 22:11

theSpyCry


Your answer is great... I just wanna say this.

I have so many controls to validate and so many rules so what i did was creating a constructor in my validationRule class and set the ValidatesOnTargetUpdated to True in there.

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

Examlpe

public class MyRule : ValidationRule
{
   public MyRule() : base() { ValidatesOnTargetUpdated = true; }
   ...
}

public class MyRule2 : MyRule 
{
   public MyRule2() : base() { }
   ...
}
like image 32
istavros Avatar answered Nov 15 '22 21:11

istavros