在一个程序中有时候文本框需要添加限制,比如需要限制文本框只能输入数字,限制文本框只能输入数字和字母等等。先来介绍文本框只能输入数字
<TextBox PreviewTextInput="UserName_PreviewTextInput" //限制输入特殊字符
PreviewKeyDown="Space_PreviewKeyDown" //限制输入空格
InputMethod.IsInputMethodEnabled="False" >
<TextBox.CommandBindings>//禁止复制粘贴
<CommandBinding Command="ApplicationCommands.Paste" CanExecute="CommandBinding_CanExecute"/>
<CommandBinding Command="ApplicationCommands.Copy" CanExecute="CommandBinding_CanExecute"/>
<CommandBinding Command="ApplicationCommands.Cut" CanExecute="CommandBinding_CanExecute"/>
</TextBox.CommandBindings>
</TextBox>
需要类
public class TextRestrict { /// <summary> /// 禁止文本框复制粘贴 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Prohibit(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = false; e.Handled = true; } /// <summary> /// 鼠标按下事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void ButtonDown(PasswordBox pwd, TextBox txt) { txt.Text = pwd.Password; txt.IsEnabled = true; txt.Visibility = Visibility.Visible; pwd.IsEnabled = false; pwd.Visibility = Visibility.Hidden; } #endregion public void SpaceKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) { e.Handled = true; } } } }
在根据textbox中的所写的属性写方法
限制输入空格
TextRestrict text = new TextRestrict();
private void Space_PreviewKeyDown(object sender, KeyEventArgs e)
{
text.SpaceKeyDown(sender, e);
}
限制特殊字符
private void UserName_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Astrict astrict = new Astrict();
astrict.Number(sender, e);
}
禁止粘贴复制
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
text.Prohibit(sender, e);
}