简体   繁体   English

WPF ValidationRules不会在加载时触发

[英]WPF ValidationRules does not fire on load

I have a ValidationRules on a textbox; 我在文本框中有一个ValidationRules

<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. 认为这是将UpdateSourceTrigger="PropertyChanged"更改为UpdateSourceTrigger="LostFocus"的简单解决方案,但不会导致ValidationRules触发。 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. 如果设置UpdateSourceTrigger="LostFocus" ,则在将输入焦点设置为另一个控件时进行验证,另一方面,每次更改文本时都会触发UpdateSourceTrigger="PropertyChanged" ,其行为与TextBox的TextChanged事件非常相似。

ValidatesOnTargetUpdated="True" ensures that the text is validated on load, your XAML code is correct. ValidatesOnTargetUpdated="True"确保在加载时验证文本,您的XAML代码正确。 If you set a breakpoint in ValueCannotBlankValidator.Validate method you would probably find it is actually fired on load. 如果在ValueCannotBlankValidator.Validate方法中设置一个断点, ValueCannotBlankValidator.Validate可能会发现它实际上是在加载时触发的。

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. 我怀疑您的验证器在第一次验证时是否返回valid结果,那时TextBox的Text属性为null ,如果将nullstring.Empty ("")进行比较,则会得到不正确的结果。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM