0

Int32.Parse在课堂上使用后ComboBoxNotEmptyValidationRule出现错误:

Input string was not in a correct format.

当我添加到 XAML 时:

<local:ComboBoxNotEmptyValidationRule x:Name="Number" ValidatesOnTargetUpdated="True"/>

程序运行正常,此验证工作正常。在设计窗口中我没有任何内容,只有FormatException: Input string was not in a correct format.消息。当我在 XAML 中评论这一行时,一切都很好。

class ComboBoxNotEmptyValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            int str = -1;
              str = Int32.Parse(value as string);
            if (str > 0)
            {
                if (str > 0)
                    return ValidationResult.ValidResult;
            }
            return new ValidationResult(false, "please fill required field");
        }
    }
4

1 回答 1

0

你可以使用int32.TryParse

class ComboBoxNotEmptyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        int str;
        if (Int32.TryParse(value as string, out str))
        {
            if (str > 0)
                return ValidationResult.ValidResult;
        }
        return new ValidationResult(false, "please fill required field");
    }
}

或者,您可以捕获FormatException并返回您的错误验证结果。

class ComboBoxNotEmptyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        int str = -1;
        try
        {
            str = Int32.Parse(value as string);
            if (str > 0)
            {
                if (str > 0)
                    return ValidationResult.ValidResult;
            }
            return new ValidationResult(false, "please fill required field");
        }
        catch (FormatException)
        {
            return new ValidationResult(false, "please fill required field");
        }
    }
}
于 2013-02-08T19:02:39.393 回答