【问题标题】:Number only TextBox (WPF) [duplicate]仅数字文本框(WPF)[重复]
【发布时间】:2011-08-05 02:13:30
【问题描述】:

可能重复:
How do I get a TextBox to only accept numeric input in WPF?

以下代码不正确:

 private  void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !AreAllValidNumericChars(e.Text);



    }
    private bool AreAllValidNumericChars(string str)
    {
        foreach (char c in str)
        {
            if (!Char.IsNumber(c)) return false;
        }

        return true;
    }

 private  void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !AreAllValidNumericChars(e.Text);

    }
    bool AreAllValidNumericChars(string str)
    {
        bool ret = true;
        if (str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PerMilleSymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol |
            str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign)
            return ret;

        int l = str.Length;
        for (int i = 0; i < l; i++)
        {
            char ch = str[i];
            ret &= Char.IsDigit(ch);
        }

        return ret;
    }

     private override void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        char c = e.Text.ToCharArray().First();
        e.Handled = !(char.IsNumber(c) || char.IsControl(c));

    }

还有.....

问题:Ctrl+V 复制/粘贴

什么是正确的代码?

【问题讨论】:

标签: wpf textbox


【解决方案1】:

这是我用于数字文本框的代码,并且工作正常。

private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = onlyNumeric(e.Text);
}

public static bool onlyNumeric(string text)
{
    Regex regex = new Regex("^[0-9]*$"); //regex that allows numeric input only
    return !regex.IsMatch(text); // 
}

【讨论】:

  • OP 在标题中声明了 WPF,并在他们的示例中使用了 C#。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多