你可以使用控件的PreviewTextInput 事件来阻止控件接收某些输入的字符。
要防止某个特定的字符输入到控件,你只要简单的设置TextCompositionEventArgs 类型参数的Handled 属性为true就可以。它将中断控件接收字符输入事件的路由。
在XAML代码中注册事件:
<TextBox Text="" HorizontalAlignment="Center" Width="150"
PreviewTextInput="TextBox_PreviewTextInput" />
CS文件代码中实现事件处理函数:
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// No e's allowed
if ((e.Text == "e") || (e.Text == "E"))
e.Handled = true;
}
在代码中,我们组织了‘e’和‘E’这两个字符的输入,在TextBox 中输入这两个字符将不会被接收。
要注意有些按键按下是不会触发PreviewTextInput 事件的,它们是:
-空格(Spacebar)
-回退(Backspace)
-Home/End/Delete/Insert 键
-方向箭头
-Ctl组合键, 比如 Ctrl+V
原文地址:https://wpf.2000things.com/2012/08/24/632-block-input-using-previewtextinput/