简体   繁体   English

文本框PreviewTextInput-仅接受数字和':'

[英]Textbox PreviewTextInput - accept only numbers and ':'

I have this code: 我有以下代码:

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

when there is only 当只有

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

I can write numbers and when I use only the second if(), I can write only ' : '. 我可以写数字,当我只使用第二个if()时,我只能写':'。 But when I use both of them I can't write anything. 但是当我同时使用它们时,我什么也写不出来。

Just use boolean logic: 只需使用布尔逻辑:

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

    break; 
  }
}

Another way to do this would be using a linq statement. 另一种方法是使用linq语句。 It comes down to personal preference but many find linq to be more readable. 它取决于个人喜好,但许多人发现linq更具可读性。

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

It's a fairly easy one liner and with the coming of c# 6 the entire method could be written as a lambda function like so: 这是一个相当简单的代码,随着c#6的到来,整个方法可以编写为lambda函数,如下所示:

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

Keep in mind that PreviewTextInput does not handle space characters and these methods will not filter them out. 请记住,PreviewTextInput不处理空格字符,并且这些方法不会将其过滤掉。 An explanation is provided on the MSDN forums MSDN论坛上提供了解释

Because some IMEs will treat whitespace keystroke as part of the text composition process, that's why it eats up by Avalon to report correct composited text through TextInput event. 由于某些IME会将空格击键视为文本编写过程的一部分,因此Avalon会吃掉它以通过TextInput事件报告正确的合成文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM