WPF 只允许输入数字的文本框

在网上有不少关入这方面的资料,下面是我选用的一个方案

public NumberTextBox()
        {
            InitializeComponent();
            this.KeyDown += NumberTextBox_KeyDown;
            this.TextChanged += NumberTextBox_TextChanged;
        }

        void NumberTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        void NumberTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);

            int offset = change[0].Offset;
            if (change[0].AddedLength > 0)
            {
                double num = 0;
                if (!Double.TryParse(this.Text, out num))
                {
                    this.Text = this.Text.Remove(offset, change[0].AddedLength);
                    this.Select(offset, 0);
                }
            }
        }

 

但是这个方案当输入法为中文的时候效果不理想,于是想到了禁用输入法。

引入xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"

 然后再 TextBox控件的xaml中  input:InputMethod.IsInputMethodEnabled="False" 就可以了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值