NumberTextBox.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System.Windows.Controls;
  2. using System.Windows.Input;
  3. namespace MuchInfo.Chart.FormulaEdit
  4. {
  5. public class NumberTextBox : TextBox
  6. {
  7. protected override void OnKeyDown(KeyEventArgs e)
  8. {
  9. base.OnKeyDown(e);
  10. if (!IsNumber((byte)e.Key))
  11. {
  12. e.Handled = true;
  13. }
  14. }
  15. protected override void OnTextChanged(TextChangedEventArgs e)
  16. {
  17. if (!string.IsNullOrEmpty(this.Text))
  18. {
  19. double number = 0d;
  20. if (!double.TryParse(this.Text, out number))
  21. {
  22. this.Text = string.Empty;
  23. }
  24. }
  25. base.OnTextChanged(e);
  26. }
  27. /// <summary>
  28. /// 输入 是否为数字
  29. /// </summary>
  30. /// <param name="key"></param>
  31. /// <returns></returns>
  32. private bool IsNumber(byte key)
  33. {
  34. // 数字
  35. if (key >= 34 && key <= 43) return true;
  36. // 小数字键盘
  37. if (key >= 74 && key <= 83) return true;
  38. // Backspace键
  39. if (key == 2) return true;
  40. return false;
  41. }
  42. }
  43. }