I have a ValidationRules
on a textbox;
<TextBox Margin="5,5,5,0" Name="myTextBox" >
<Binding Path="myID" NotifyOnValidationError="True" ValidatesOnDataErrors="True" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<local:ValueCannotBlankValidator ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
Now this works if the user changes the value in the textbox. The problems that it doesn't fire on load. Figured it would be a simple fix of changing UpdateSourceTrigger="PropertyChanged"
to UpdateSourceTrigger="LostFocus"
but that causes the ValidationRules
not to fire. Thanks for the help.
If you set UpdateSourceTrigger="LostFocus"
, the validation happens when input focus is set to another control, on the other hand, UpdateSourceTrigger="PropertyChanged"
fires every time the text is changed, acts much like a TextBox's TextChanged event.
ValidatesOnTargetUpdated="True"
ensures that the text is validated on load, your XAML code is correct. If you set a breakpoint in ValueCannotBlankValidator.Validate
method you would probably find it is actually fired on load.
I doubt your validator returns a valid
result at the first validation, at that moment the Text property of the TextBox is null
, if you compare null
against string.Empty ("")
, you get an incorrect result.
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
ValidationResult trueResult = new ValidationResult(true, "not blank");
string str = value as string; //value is null on load, don't compare it against ""
if (string.IsNullOrEmpty(str))
return new ValidationResult(false, "blank");
else
return trueResult;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.