WPF文本框只允许输入数字

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

01 XAML代码
02  
03 < TextBox Height="23" HorizontalAlignment="Left" Margin="100,5,0,0" Name="textBox1"VerticalAlignment="Top" Width="120"
04                  DataObject.Pasting="textBox1_Pasting"PreviewKeyDown="textBox1_PreviewKeyDown" InputMethod.IsInputMethodEnabled="False"
05                    PreviewTextInput="textBox1_PreviewTextInput"
06                  / >
07  
08   
09  
10   
11  
12 cs代码
13  
14   
15  
16 //检测粘贴
17         private void textBox1_Pasting(object sender, DataObjectPastingEventArgs e)
18         {
19             if (e.DataObject.GetDataPresent(typeof(String)))
20             {
21                 String text = (String)e.DataObject.GetData(typeof(String));
22                 if (!isNumberic(text))
23                 { e.CancelCommand(); }
24             }
25             else { e.CancelCommand(); }
26         }
27  
28   
29  
30         private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
31         {
32             if (e.Key == Key.Space)
33                 e.Handled = true;
34         }
35  
36   
37  
38         private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
39         {
40             if (!isNumberic(e.Text))
41             {
42                 e.Handled = true;
43             }
44             else
45                 e.Handled = false;
46         }
47  
48  
49         //isDigit是否是数字
50         public static bool isNumberic(string _string)
51         {
52             if (string.IsNullOrEmpty(_string))
53                 return false;
54             foreach (char in _string)
55             {
56                 if (!char.IsDigit(c))
57                     //if(c<'0' c="">'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
58                     return false;
59             }
60             return true;
61         }

你可能感兴趣的:(WPF文本框只允许输入数字)