【发布时间】:2016-07-12 03:03:06
【问题描述】:
我正在尝试限制除英文字母之外的所有字符,但我仍然可以输入一些不好的顽皮字符!我怎样才能防止这种情况。我的正则表达式没有捕捉到这些顽皮的字符是- _ + = ? < > '。
private void AlphaOnlyTextBox_OnKeyDown(object sender, KeyEventArgs e)
{
var restrictedChars = new Regex(@"[^a-zA-Z\s]");
var match = restrictedChars.Match(e.Key.ToString());
// Check for a naughty character in the KeyDown event.
if (match.Success)
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="21"
Width="77"
MaxLength="2"
KeyDown="AlphaOnlyTextBox_OnKeyDown"
>
</TextBox>
</Grid>
</Window>
【问题讨论】:
-
正则表达式似乎抓住了那些(在 regexr.com 上测试过)。你确定问题不在其他地方吗?
-
是的,问题must be somewhere else。
-
@rtmh 您可以在 WPF/C# 中轻松构建问题。由于某些奇怪的原因,它不起作用!
-
@rtmh 一个建议!也许它与按下 Shift 按钮有关!因为我们需要按那个来输入+?
-
我不会说我们可以轻松构建它。至于那个问题,请查看 KeyEventArgs::Key 函数的细节,它是否返回您期望的结果?