zoukankan      html  css  js  c++  java
  • WPF文本框只允许输入数字[转]

    转自:http://www.oschina.net/code/snippet_565270_10848

    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;
            }
    本博客所有博文,若无专门说明皆为原创,转载请注明作者和出处!
  • 相关阅读:
    CodeForces666E Forensic Examination
    #46. 【清华集训2014】玄学
    #207. 共价大爷游长沙
    BZOJ4259残缺的字符串
    [六省联考2017]分手是祝愿
    BZOJ2616PERIODNI
    UVa 1363 Joseph's Problem (等差数列)
    UVa 1641 ASCII Area
    UVa 10213 How Many Pieces of Land? (组合数学 & 图论)
    UVa 1640 The Counting Problem (数位DP)
  • 原文地址:https://www.cnblogs.com/ifinver/p/2955806.html
Copyright © 2011-2022 走看看