限制TextBox输入,只能输入整数
1 public class TextBoxInt : TextBox 2 { 3 public TextBoxInt() 4 { 5 KeyDown += TextBoxInt_KeyDown; 6 TextChanged += TextBoxInt_TextChanged; 7 } 8 9 private void TextBoxInt_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 int num; 22 if (!int.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 TextBoxInt_KeyDown(object sender, KeyEventArgs e) 32 { 33 if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) 34 { 35 // 允许输入数字小键盘上的数字0-9 36 e.Handled = false; 37 } 38 else if ((e.Key >= Key.D0 && e.Key <= Key.D9) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift) 39 { 40 // 允许输入数字0-9,并且不能同时按着Shift键 41 e.Handled = false; 42 } 43 else if (e.Key == Key.Enter) 44 { 45 // 允许输入回车 46 e.Handled = false; 47 } 48 else 49 { 50 e.Handled = true; 51 } 52 } 53 }