简体   繁体   中英

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 ' : '. 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. It comes down to personal preference but many find linq to be more readable.

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:

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. An explanation is provided on the MSDN forums

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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