ValidationRule 和 UpdateSourceTrigger=LostFocus 在文本框失去焦点时不会触发

ValidationRule with UpdateSourceTrigger=LostFocus not firing when textbox loses focus

提问人:Tim Jones 提问时间:8/18/2023 最后编辑:Lukasz SzczygielekTim Jones 更新时间:8/19/2023 访问量:36

问:

我正在尝试在 WPF 应用程序中实现表单数据的验证。

视图

<StackPanel Orientation="Horizontal" Margin="0 5 0 5">
    <TextBlock Style="{StaticResource FormLabel}" Text="Agency:"/>
    <TextBox x:Name="agency" Style="{StaticResource InputBox}" Margin="10 0 10 0"
                    Width="214" TabIndex="1" >
        <Binding Path="Agency" UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <validationrules:RequiredValidationRule FieldName="Agency"/>
            </Binding.ValidationRules>
        </Binding> 
    </TextBox>
</StackPanel>

验证规则

public class RequiredValidationRule : ValidationRule
{
    public static string GetErrorMessage(string fieldName, object fieldValue, object nullValue = null)
    {
        string errorMessage = string.Empty;
        if (nullValue != null && nullValue.Equals(fieldValue))
            errorMessage = string.Format("You cannot leave the {0} field empty.", fieldName);
        if (fieldValue == null || string.IsNullOrEmpty(fieldValue.ToString()))
            errorMessage = string.Format("You cannot leave the {0} field empty.", fieldName);
        return errorMessage;
    }

    public string FieldName { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string error = GetErrorMessage(FieldName, value);
        if (!string.IsNullOrEmpty(error))
            return new ValidationResult(false, error);
        return ValidationResult.ValidResult;
    }
}

我在验证规则中放置了一个断点,发现如果我按 Tab 键或单击到 TextBox,然后单击或按 Tab 键离开,则不会触发验证规则。但是,如果我按 Tab 键或单击到 TextBox,键入某些内容,将其删除,然后按 Tab 键离开它就可以工作了。

我已经使用 GotFocus 和 LostFocus 的虚拟事件验证了 TextBox 焦点是否正在适当更改。

我需要验证规则,如果盒子失去焦点,即使没有输入任何内容,我也会触发。有没有可能这样做,我哪里出了问题?

C# WPF XAML 验证规则

评论


答:

1赞 Lukasz Szczygielek 8/19/2023 #1

声明验证规则时,请将 ValidatesOnTargetUpdated 设置为 。true

<validationrules:RequiredValidationRule ValidatesOnTargetUpdated="True" FieldName="Agency"/>