WPF中自定义只能输入数字的TextBox
wpf textbox控制只输入数字
KeyDown事件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) 2 { 3 TextBox txt = sender as TextBox; 4 5 //屏蔽非法按键 6 if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal) 7 { 8 if (txt.Text.Contains(".") && e.Key == Key.Decimal) 9 { 10 e.Handled = true; 11 return; 12 } 13 e.Handled = false; 14 } 15 else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift) 16 { 17 if (txt.Text.Contains(".") && e.Key == Key.OemPeriod) 18 { 19 e.Handled = true; 20 return; 21 } 22 e.Handled = false; 23 } 24 else 25 { 26 e.Handled = true; 27 } 28 }
TextChanged事件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 2 { 3 //屏蔽中文输入和非法字符粘贴输入 4 TextBox textBox = sender as TextBox; 5 TextChange[] change = new TextChange[e.Changes.Count]; 6 e.Changes.CopyTo(change, 0); 7 8 int offset = change[0].Offset; 9 if (change[0].AddedLength > 0) 10 { 11 double num = 0; 12 if (!Double.TryParse(textBox.Text, out num)) 13 { 14 textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength); 15 textBox.Select(offset, 0); 16 } 17 } 18 }