【问题标题】:Textbox PreviewTextInput - accept only numbers and ':'文本框 PreviewTextInput - 只接受数字和 ':'
【发布时间】:2021-07-08 15:59:09
【问题描述】:

我有这个代码:

foreach (char ch in e.Text)
        {
            if (!Char.IsDigit(ch))
                e.Handled = true;
            else
            {
                if(!(ch.Equals(':')))
                    e.Handled = true;
            }
        }

当只有时

if (!Char.IsDigit(ch))
                e.Handled = true;

我可以写数字,当我只使用第二个 if() 时,我只能写 ' : '。 但是当我同时使用它们时,我什么也写不出来。

【问题讨论】:

    标签: c# wpf textbox


    【解决方案1】:

    只需使用布尔逻辑:

    foreach (var ch in e.Text)
    {
        if (!(Char.IsDigit(ch) || ch.Equals(':')))
        {
            e.Handled = true;
            break;
        }
    }
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用 linq 语句。这取决于个人喜好,但许多人发现 linq 更具可读性。

      e.Handled = !e.Text.Any(x => Char.IsDigit(x) || ':'.Equals(x));
      

      这是一个相当简单的单行程序,随着 c# 6 的到来,整个方法可以写成一个 lambda 函数,如下所示:

      private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) =>
          e.Handled = !e.Text.Any(x => Char.IsDigit(x) || ':'.Equals(x));
      

      请记住,PreviewTextInput 不处理空格字符,并且这些方法不会将它们过滤掉。 MSDN forums上提供了解释

      因为某些 IME 会将空格键击视为文本合成过程的一部分,这就是为什么 Avalon 会通过 TextInput 事件报告正确的合成文本。

      【讨论】:

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