限制TextBox输入,只能输入Double类型数字

 1      public class TextBoxDouble : TextBox
 2     {
 3         public TextBoxDouble()
 4         {
 5             KeyDown += TextBoxDouble_KeyDown;
 6             TextChanged += TextBoxDouble_TextChanged;
 7         }
 8 
 9         private void TextBoxDouble_TextChanged(object sender, TextChangedEventArgs e)
10         {
11             //屏蔽非法字符粘贴
12             var textBox = sender as TextBox;
13             if (textBox != null)
14             {
15                 var change = new TextChange[e.Changes.Count];
16                 e.Changes.CopyTo(change, 0);
17 
18                 int offset = change[0].Offset;
19                 if (change[0].AddedLength > 0)
20                 {
21                     double num;
22                     if (!Double.TryParse(textBox.Text, out num))
23                     {
24                         textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
25                         textBox.Select(offset, 0);
26                     }
27                 }
28             }
29         }
30 
31         private void TextBoxDouble_KeyDown(object sender, KeyEventArgs e)
32         {
33             var txt = sender as TextBox;
34             if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal)
35             {
36                 // 允许输入小键盘数字0-9或者点号
37                 if (txt != null && (txt.Text.Contains(".") && e.Key == Key.Decimal))
38                 {
39                     // 不允许输入多个点号
40                     e.Handled = true;
41                     return;
42                 }
43                 e.Handled = false;
44             }
45             else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) &&
46                      e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
47             {
48                 // 允许输入数字0-9或者点号 并且不能按着Shift
49                 if (txt != null && (txt.Text.Contains(".") && e.Key == Key.OemPeriod))
50                 {
51                     // 不允许输入多个点号
52                     e.Handled = true;
53                     return;
54                 }
55                 e.Handled = false;
56             }
57             else if (e.Key == Key.Enter)
58             {
59                 // 允许输入回车
60                 e.Handled = false;
61             }
62             else
63             {
64                 e.Handled = true;
65             }
66         }
67     }

 

posted @ 2013-12-03 13:33  CandyZkn  阅读(1246)  评论(0编辑  收藏  举报