TextBox只允许使用数字

来源:互联网 发布:怎么给淘宝店刷好评 编辑:程序博客网 时间:2024/05/06 20:33

wpf的Textbox只允许输入数字,android一个属性就搞定了,wpf还有监听按键,监听内容

第一个方法,禁止输入其他字符,第二个方法可以粘贴非法字符

        private void TextBox_KeyDownIsNum(object sender, KeyEventArgs e)        {            TextBox txt = sender as TextBox;            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))            {                e.Handled = false;                return;            }            else if (e.Key >= Key.D0 && e.Key <= Key.D9)            {                e.Handled = false;                return;            }            else            {                e.Handled = true;            }        }        private void TextBox_TextChangedIsNum(object sender, TextChangedEventArgs e)        {            TextBox textBox = sender as TextBox;            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(textBox.Text, out num))                {                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);                    textBox.Select(offset, 0);                }            }        }

2014-01-10:

这种方法存在问题,请不要使用

以使用OnPreviewXXX方法,按照wpf路由事件的顺序进行验证。

具体可以查看wpf空间中的OnPreviewXXX。

原创粉丝点击