如何让wpf 中的textbox只能输入整型或浮点型

来源:互联网 发布:python socket服务端 编辑:程序博客网 时间:2024/06/03 12:52

不使用正则表达式

        bool isNotnum = false;        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)        {            ((TextBox)sender).ImeMode = ImeMode.Disable;            this.isNotnum = false;            ((TextBox)sender).Tag = ((TextBox)sender).Text;            //允许输入数字、小数点和删除键            if((e.KeyChar<48||e.KeyChar>57) && e.KeyChar!=8&&e.KeyChar!=(char)('.'))            {                e.Handled = true;                this.isNotnum = true;            }            //小数点只能输入一次            if(e.KeyChar ==(char)('.')&&((TextBox)sender).Text.IndexOf('.')!=-1)            {                e.Handled = true;            }            //第一位不能为小数点            if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")            {                e.Handled = true;            }            //第一位是0,第二位必须为小数点            if (e.KeyChar != (char)('.') && ((TextBox)sender).Text == "0")            {                e.Handled = true;            }            if(e.KeyChar == 8)            {                e.Handled = false;            }            //只允许输入数字            if (e.KeyChar >= 0x4e00 && e.KeyChar <= 0x9fa5)            {                this.isNotnum = true;            }        }        private void textBox1_KeyUp(object sender, KeyEventArgs e)        {            if (this.isNotnum && ((TextBox)sender).Text != ((TextBox)sender).Text.ToString())            {                MessageBox.Show("只能输入数字!!!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Question);                ((TextBox)sender).Text = ((TextBox)sender).Tag.ToString();                ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;                this.isNotnum = false;                return;            }        }    }


 

来自百度:http://zhidao.baidu.com/question/59975921.html