wpf验证规则:使用点而不是逗号验证整数

时间:2010-10-30 16:23:24

标签: wpf validation

我正在开发一个c#wpf应用程序,我希望在文本框中验证用户输入。我有一个像这样的验证规则:

public class NumericRule : ValidationRule
{
    /// <summary>
    /// Checks whether a value can be converted to a numeric value.
    /// </summary>
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string input = value as string;

        //try conversion
        int result;
        var status = int.TryParse(input, NumberStyles.Any,
                                  CultureInfo.InvariantCulture, out result);

        //return valid result if conversion succeeded
        return status ? ValidationResult.ValidResult
                      : new ValidationResult(false, input + " is not a number");
    }
}

但是,输入带有小数的数字(如3.5)时,表示该数字无效。输入3,5即可。我希望这两个数字都有效,如果输入带逗号的值,则将其转换为点。另外我想在点之后最多有3位小数。

任何帮助?

由于

1 个答案:

答案 0 :(得分:1)

我想你要解析为double。如果你想要“,”和“。”作为分隔符,您可以查看多种文化。将您需要支持的文化添加到列表中。

public class NumericRule : ValidationRule
{
    private readonly List<CultureInfo> cultures = new List<CultureInfo> {
        CultureInfo.CurrentCulture,
        CultureInfo.CurrentUICulture,
        CultureInfo.InvariantCulture
    };

    public override ValidationResult Validate (object value, CultureInfo cultureInfo)
    {
        string input = (string)value;

        bool success = false;
        foreach (CultureInfo culture in cultures) {
            double result;
            if (double.TryParse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, culture, out result)) {
                int decimalPos = input.IndexOf(culture.NumberFormat.NumberDecimalSeparator);
                if (decimalPos == -1) {
                    success = true;
                    break;
                }
                if (input.Substring(decimalPos + 1).Length > 3)
                    return new ValidationResult(false, "Too many digits in " + input);
                success = true;
                break;
            }
        }
        return success ? ValidationResult.ValidResult : new ValidationResult(false, input + " is not a number");
    }
}