【问题标题】:Windows 8 - TextBox that only accepts numbers goes wrongWindows 8 - 只接受数字的文本框出错
【发布时间】:2016-06-21 01:18:44
【问题描述】:

这是我用 C# 编写的带有 Key Down 事件处理程序的 TextBox

private void TextBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
        //ONLY ACCEPTS NUMBERS
        char c = Convert.ToChar(e.Key);
        if (!c.Equals('0') && !c.Equals('1') && !c.Equals('2') && !c.Equals('3') && !c.Equals('4') &&
            !c.Equals('5') && !c.Equals('6') && !c.Equals('7') && !c.Equals('8') && !c.Equals('9'))
        {
            e.Handled = true;
        }
}

它确实可以防止字母从 a 到 z。但是,如果我输入像 !@#$%^&*()_+ 这样的符号,它仍然会接受它们。我错过了什么?

【问题讨论】:

    标签: windows-8 textbox numbers


    【解决方案1】:

    您可以使用Char.IsDigit

    e. Handled = !Char.IsDigit(c);
    

    但这在复制\粘贴的情况下对您没有多大帮助。

    同时检查右侧的相关问题。例如Create WPF TextBox that accepts only numbers


    更新

    只写字母试试

    e.Handled = Char.IsLetter(c);
    

    【讨论】:

    • 也忽略数字键盘:(
    【解决方案2】:

    没有可靠的方法来处理按键按下或按键向上事件,因为由于某些奇怪的原因 shift 4 即 $ 符号返回 4 而不是键值。

    最好的解决方法是在使用之前捕获该值并检查它是否为数字,然后提醒用户。

    var IsNumeric = new System.Text.RegularExpressions.Regex("^[0-9]*$");
            if (!IsNumeric.IsMatch(edtPort.Text))
            {
                showMessage("Port number must be number", "Input Error");
                return;
            }
    

    尝试告诉您的用户美元符号现在是一个数字,这绝不是理想的,但更好!

    【讨论】:

      【解决方案3】:

      试试这个代码。但有时您会看到您按下的 char 并立即将其删除。不是最好的解决方案,但足够了

      private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
      {
          var textBox = sender as TextBox;
          if (textBox == null)
              return;
      
          if (textBox.Text.Length == 0) return;
      
          var text = textBox.Text;
      
          int result;
          var isValid = int.TryParse(text, out result);
          if (isValid) return;
      
      
          var selectionStart = textBox.SelectionStart;
          var resultString = new string(text.Where(char.IsDigit).ToArray());
          var lengthDiff = textBox.Text.Length - resultString.Length;
      
          textBox.Text = resultString;
          textBox.SelectionStart = selectionStart - lengthDiff;
      }
      

      【讨论】:

        【解决方案4】:

        这可能会有所帮助,这是我使用的。

            private void txtBoxBA_KeyDown(object sender, KeyRoutedEventArgs e)
            {
                // only allow 0-9 and "."
                e.Handled = !((e.Key.GetHashCode() >= 48 && e.Key.GetHashCode() <= 57));
        
                // check if "." is already there in box.
                if (e.Key.GetHashCode() == 190)
                    e.Handled = (sender as TextBox).Text.Contains(".");
            }
        

        【讨论】:

          猜你喜欢
          • 2022-06-28
          • 2011-06-15
          • 1970-01-01
          • 2013-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-19
          • 2015-12-30
          相关资源
          最近更新 更多