码迷,mamicode.com
首页 > Windows程序 > 详细

WPF文本框只允许输入数字

时间:2018-03-06 18:19:40      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:左右   idt   ==   type   tao   height   put   position   present   

XAML代码

 
< TextBox Height="23" HorizontalAlignment="Left" Margin="100,5,0,0" Name="textBox1" VerticalAlignment="Top"
Width="120" DataObject.Pasting="textBox1_Pasting" PreviewKeyDown="textBox1_PreviewKeyDown"
InputMethod.IsInputMethodEnabled="False" PreviewTextInput="textBox1_PreviewTextInput"/ >
 
  
 
  
 
cs代码
 
  
 
//检测粘贴
        private void textBox1_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(String)))
            {
                String text = (String)e.DataObject.GetData(typeof(String));
                if (!isNumberic(text))
                { e.CancelCommand(); }
            }
            else { e.CancelCommand(); }
        }
 
  
 
        private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
                e.Handled = true;
        }
 
  
 
        private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!isNumberic(e.Text))
            {
                e.Handled = true;
            }
            else
                e.Handled = false;
        }
 
 
        //isDigit是否是数字
        public static bool isNumberic(string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            foreach (char c in _string)
            {
                if (!char.IsDigit(c))
                    //if(c<‘0‘ c="">‘9‘)//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
                    return false;
            }
            return true;
        }

WPF文本框只允许输入数字

标签:左右   idt   ==   type   tao   height   put   position   present   

原文地址:https://www.cnblogs.com/kid526940065/p/8515896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!