C# WPF下限制TextBox只输入数字、小数点、删除等键

C#中限制TextBox只输入数字和小数点的方法不止一种,有正则表达、 ASCII码,还有通过Key和ModifierKeys的。这里讲讲通过Key和ModifierKeys来进行输入限制。
Key是C#下的枚举类型,枚举了所有的键盘键,如D0到D9为0到9的按键,Key.Delete代表的是删除键,Key.OemPeriod为小数点。 ModifierKeys也是C#下的枚举类型,包括Alt、Ctrl、Shift等键。如下:
public enum ModifierKeys{
   None=0,        //没有按下任何修饰符
   Alt=1,             //Alt键
   Control=2,     //Ctrl键
   Shift=4,         //Shift键
   Windows=8,   //Windows徽标键
   Apple=8,       //按下Apple键徽标键
    }
TextBox通过PreviewKeyDown和KeyDown捕获按下的键值,TextChanged获取已经发生变化的TextBox的值和对应的Changed。另外需要通过: InputMethod.IsInputMethodEnabled ="False",屏蔽输入法。

代码如下:
public static bool isInputNumber(KeyEventArgs e)
        {
            if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ||
               e.Key==Key.Delete || e.Key == Key.Back || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.OemPeriod)
            {
                //按下了Alt、ctrl、shift等修饰键
                if (e.KeyboardDevice.Modifiers != ModifierKeys.None)
                {
                    e.Handled = true;
                }
                else
                {
                    return true;
                }
               
            }
            else//按下了字符等其它功能键
            {
                e.Handled = true;
            }
            return false;
        }
PreviewKeyDown事件处理:
 private void textBoxBuyPercent_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!CommonFun.isInputNumber(e))
            {
                MessageBox.Show("请输入数字!");
            }
        }
屏蔽输入法:
<TextBox Name="textBoxBuyPrice" Grid.Row="3" Grid.Column="2" Text="{Binding BuyPrice}" HorizontalAlignment="Left" Height="23"  VerticalAlignment="Center" TextChanged="textBoxBuyPrice_TextChanged" PreviewKeyDown="textBoxBuyPrice_PreviewKeyDown"  InputMethod.IsInputMethodEnabled="False" Width=" 80"/>





猜你喜欢

转载自blog.csdn.net/mpegfour/article/details/79680355