只能输入数字的TextBox控件

最近做项目用到了只能输入数字的TextBox控件,于是自己百度了一下,最终总结如下:
</pre><pre name="code" class="csharp">        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (this.IsOnlyNumber)
            {
                // 屏蔽非法按键
                if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key == Key.Back)
                {
                    if (this.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.Key == Key.Back) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
                {
                    if (this.Text.Contains(".") && e.Key == Key.OemPeriod)
                    {
                        e.Handled = true;
                        return;
                    }

                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                }
            }

            base.OnPreviewKeyDown(e);
        }

        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            if (this.IsOnlyNumber)
            {
                if (!this.isNumberic(e.Text))
                {
                    e.Handled = true;
                }
                else
                {
                    e.Handled = false;
                }
            }

            base.OnPreviewTextInput(e);
        }

        private bool isNumberic(string _string)
        {
            if (string.IsNullOrEmpty(_string))
            {
                return false;
            }

            foreach (char c in _string)
            {
                if (!char.IsDigit(c))
                {
                    return false;
                }
            }

            return true;
        }

上述方法不能排除输入中文,因此又在网上搜了一下,禁用了输入法,方法如下:

在使用TextBox的界面先引用

xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
然后在TextBox控件中增加属性

input:InputMethod.IsInputMethodEnabled="False"
至此搞定。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值