1 功能要求
- 仅能输入数字和小数点。
- 禁用复制、剪切、粘贴。
- 禁用输入法。
2 功能设计
数字输入框基于TextBox。
2.1 仅能输入数字和小数点
处理键盘按下事件
TextBox txt = sender as TextBox;
//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal)
{
if (txt.Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) &&
e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
if (txt.Text.Contains(".") && e.Key == Key.OemPeriod)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else
{
e.Handled = true;
}
2.2 禁用复制、剪切、粘贴功能
(1)添加命令绑定
<TextBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste" CanExecute="NumericBox_CommandBinding_CanExecute"></CommandBinding>
<CommandBinding Command="ApplicationCommands.Cut" CanExecute="NumericBox_CommandBinding_CanExecute"></CommandBinding>
<CommandBinding Command="ApplicationCommands.Copy" CanExecute="NumericBox_CommandBinding_CanExecute"></CommandBinding>
</TextBox.CommandBindings>
添加绑定处理函数NumericBox_CommandBinding_CanExecute
/// <summary>
/// 禁止文本框使用复制、粘贴、剪切功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NumericBox_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}
- 禁用鼠标右键快捷菜单
TextBox添加属性:
ContextMenu="{ x:Null}"
2.3 禁用输入法
TextBox添加属性:
InputMethod.IsInputMethodEnabled="False"
3 备注
可以通过修改限制字符,将控件更改为其他类型输入框。