代码之家  ›  专栏  ›  技术社区  ›  Tim Jones

ValidationRule with UpdateSourceTrigger=LostFocus当文本框失去焦点时未激发

  •  0
  • Tim Jones  · 技术社区  · 2 年前

    我正在尝试在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;
        }
    }
    

    我在验证规则中放置了一个断点,发现如果我在TextBox中制表或单击,然后单击或制表,则验证规则不会启动。但是,如果我在TextBox中打标签或单击,键入一些内容,删除它,然后用标签将其删除,它就可以工作了。

    我已经用GotFocus和LostFocus的伪事件验证了TextBox焦点的变化是否适当。

    如果框失去焦点,即使没有输入任何内容,我也需要启动验证规则。有可能做到这一点吗?我哪里错了?

    0 回复  |  直到 2 年前
        1
  •  1
  •   Lukasz Szczygielek    2 年前

    当您声明验证规则时,设置 ValidatesOnTargetUpdated true

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