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 { _validationT开发者_如何学编程ype = 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)
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"/>
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() { }
...
}
精彩评论