TextBox入力を制限し、Doubleタイプの数字しか入力できません

9418 ワード

 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     }