自定义验证:返回ValidationResult(true,null)仍然无法验证

时间:2016-05-05 09:47:54

标签: c# wpf validation

我正在输入一个通过我的自定义验证检查的值,但WPF仍会显示失败消息:

enter image description here

验证码解析百分比,转换为double。使用调试器,我可以单步执行,一切正常。对于值“50%”,它会解析0.5,逐步执行并到达最后一行return new ValidationResult(true, null);

但是,它仍会导致验证失败,并且无法转换默认消息“值'50%'。”。

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        double valueToValidate = 0;

        try
        {
            string trimmed = (value as string).TrimEnd(new char[] { '%', ' ' });
            valueToValidate = Double.Parse(trimmed) / 100;
        }
        catch (Exception e)
        {
            return new ValidationResult(false, "Illegal characters or " + e.Message);
        }

        if ((valueToValidate < Min) || (valueToValidate > Max))
        {
            return new ValidationResult(false,
              "Please enter a value in the range: " + Min + " - " + Max + ".");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }

XAML:

                        <TextBox Grid.Column="2" Width="45">
                            <TextBox.Text>
                                <Binding Path="AppController.Zoom" StringFormat="{}{0:P0}">
                                    <Binding.ValidationRules>
                                        <helpers:MinMaxPercentageValidationRule Min="0.4" Max="2"/>
                                    </Binding.ValidationRules>
                                </Binding>
                            </TextBox.Text>
                        </TextBox>

故障状态正常,提示相应的消息。它似乎只是

1 个答案:

答案 0 :(得分:0)

在.NET Framework中:

return ValidationResult.ValidResult;

在.NET Core中:

return ValidationResult.Success;