【问题标题】:Restricting characters in a TextBox限制文本框中的字符
【发布时间】:2012-05-01 14:54:07
【问题描述】:

我正在 C# WinRT 应用程序中构建一个表单,我想将其中一个 TextBox 组件中的字符限制为仅数字。 (此文本框将供用户输入年份。)

我已经搜索了一段时间,但是如果没有在 TextChanged 事件上设置事件侦听器并在每次按键时检查 text 属性,我就无法弄清楚这一点。有没有办法简单地说用户只能在 TextBox 中输入特定字符?

【问题讨论】:

    标签: c# windows-8 microsoft-metro windows-runtime


    【解决方案1】:

    可能可行的最简单的方法是绑定到OnTextChanged 事件并根据您的规则修改文本。

        <TextBox x:Name="TheText" TextChanged="OnTextChanged" MaxLength="4"/>
    
        private void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            if (TheText.Text.Length == 0) return;
    
            var text = TheText.Text;
    
            int result;
            var isValid = int.TryParse(text, out result);
            if (isValid) return;
    
            TheText.Text = text.Remove(text.Length - 1);
            TheText.SelectionStart = text.Length;
        }
    

    但是,我会回避这种方法,因为 Metro 的口号是触摸优先 UI,您可以使用 FlipView 控件以触摸优先的方式轻松实现。

    【讨论】:

    • 将此标记为答案,因为它主要解决了我遇到的问题。这会将 TextBox 限制为仅显示数字。但是,此后我重新访问了我的应用程序的这一部分,并用 ComboBox 替换了 year 字段,以完全回避这个问题。 (我可能有一个固定的年份范围,所以我不知道为什么我一开始没有使用 ComboBox。)
    【解决方案2】:

    尝试将 TextBox.InputScope 属性设置为 InputScopeNameValue.Number,如 MSDN 中的 Guidelines and checklist for text input 中所述。

    【讨论】:

    • 这很酷,而且(有点)WPF 中也存在。不知道这个。谢谢!
    • 这有点工作,但不会完全符合我的目标。看起来 InputScope 属性更像是向系统提示系统应该显示哪个软键盘,但它不会创建限制输入的屏蔽文本框。 (终于在 MSDN 论坛中找到了这个主题 - 下面的链接,请参阅 Chipalo Street 的帖子,从 2012 年 3 月 22 日星期四下午 5:49 开始)。 social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/…
    • 啊,好像我误解了文档。感谢您指出这一点。
    【解决方案3】:

    有效年份

    DateTime newDate;
    var validYear = DateTime.TryParseExact("2012", "yyyy", CultureInfo.InvariantCulture, 
    DateTimeStyles.None, out newDate); //valid
    

    无效年份

    var validYear = DateTime.TryParseExact("0000", "yyyy", CultureInfo.InvariantCulture, 
    DateTimeStyles.None, out newDate); //invalid
    

    【讨论】:

      【解决方案4】:

      这似乎对我有用:

          private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
          {
              if ((e.Key < VirtualKey.Number0) || (e.Key > VirtualKey.Number9))
              {
                  // If it's not a numeric character, prevent the TextBox from handling the keystroke
                  e.Handled = true;
              }
          }
      

      有关所有值,请参阅 VirtualKey enumeration 的文档。

      【讨论】:

        【解决方案5】:

        根据link 的帖子,添加标签以允许导航。

        private void decimalTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
            {
                bool isGoodData;    // flag to make the flow clearer.
                TextBox theTextBox = (TextBox)sender;  // the sender is a textbox
        
                if (e.Key>= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9)  // allow digits
                    isGoodData = true;
                else if (e.Key == Windows.System.VirtualKey.Tab)
                    isGoodData = true; 
                else if (e.Key >= Windows.System.VirtualKey.NumberPad0 && e.Key <= Windows.System.VirtualKey.NumberPad9)  // allow digits
                    isGoodData = true;
                else if (e.Key == Windows.System.VirtualKey.Decimal || (int)e.Key == 190)   // character is a decimal point, 190 is the keyboard period code
                                                                                            // which is not in the VirtualKey enumeration
                {
                    if (theTextBox.Text.Contains("."))   // search for a current point
                        isGoodData = false;    // only 1 decimal point allowed
                    else
                        isGoodData = true;     // this is the only one.
                }
                else if (e.Key == Windows.System.VirtualKey.Back)  // allow backspace
                    isGoodData = true;
                else
                    isGoodData = false;   // everything else is bad
                if (!isGoodData)          // mark bad data as handled
                    e.Handled = true;
            }
        

        【讨论】:

        • Shift-4,应该是一个美元符号,没有被这段代码过滤掉。 4 键被视为数字并被接受。请参阅此问题:stackoverflow.com/questions/13001215/…,其中显示了用于检测移位、控制等键的各种方法。
        【解决方案6】:

        使用 MaskedTextBox 控件。仅对于数字,只需使用 Mask 属性来指定字符和长度(如果有)。例如如果您只想输入五个数字,请将 mask 属性设置为“00000”。就那么简单。 Windows 会为您处理限制。

        【讨论】:

        猜你喜欢
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多