我试图限制除英文字母以外的所有字符,但我仍然可以输入一些顽皮的字符,这不太好!我怎样才能防止这种情况发生。这些顽皮的字符没有被我的正则表达式捕获是 - _ + = ? < > '
。
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>
最佳答案
尝试这个表达式:
var restrictedChars = new Regex(@"[^(\W_0-9)]+");
它将排除除大写字母和小写字母字符之外的所有内容(不取决于特定语言)。
希望对你有帮助!
关于c# - WPF 中的 KeyDown 事件中使用正则表达式不限制某些特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38313281/