wpf 文本框 PreviewTextInput - 只接受数字和 ':'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21814253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Textbox PreviewTextInput - accept only numbers and ':'
提问by Datsheep
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.
我可以写数字,当我只使用第二个 if() 时,我只能写 ':'。但是当我同时使用它们时,我无法写任何东西。
回答by Dmitry Bychenko
Just use boolean logic:
只需使用布尔逻辑:
foreach(var ch in e.Text) {
if (!((Char.IsDigit(ch) || ch.Equals(':'))) {
e.Handled = true;
break;
}
}
回答by Liam Morrow
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.
另一种方法是使用 linq 语句。这归结为个人喜好,但许多人发现 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. An explanation is provided on the MSDN forums
请记住,PreviewTextInput 不处理空格字符,并且这些方法不会将它们过滤掉。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 事件报告正确的组合文本的原因。

