Windows 8应用程序中Numericbox的替代品?

前端之家收集整理的这篇文章主要介绍了Windows 8应用程序中Numericbox的替代品?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在 Windows 8磁贴应用程序中找到一个很好的替代NumericBox.我尝试使用与Windows窗体相同的数字框,但得到一个错误,说明Windows 8应用程序不支持这些(?).我注意到tile应用程序的TextBox元素有一个可以设置为“Number”的InputScope,但它仍然允许用户键入他想要的任何字符.我假设InputScope没有做我认为它做的事情.

我目前正在管理文本框,但因为我正在进行计算,所以当我想要更新界面时,文本必须不断转换为十进制,然后返回文本,此外还必须执行多项检查以确保用户确实不输入非数字字符.这变得非常乏味,并且非常熟悉Windows Form,这似乎是朝着错误方向迈出的一步.我一定错过了一些明显的东西?

我不熟悉NumericTextBox,但这是一个简单的C#/ XAML实现,只允许数字和小数字符.

它只是覆盖OnKeyDown事件;基于被按下的键,它允许或不允许事件到达基本TextBox类.

我应该注意,这个实现适用于Windows应用商店应用 – 我相信你的问题是关于那种类型的应用,但我不是100%肯定.

  1. public class MyNumericTextBox : TextBox
  2. {
  3. protected override void OnKeyDown(KeyRoutedEventArgs e)
  4. {
  5. HandleKey(e);
  6.  
  7. if (!e.Handled)
  8. base.OnKeyDown(e);
  9. }
  10.  
  11. bool _hasDecimal = false;
  12. private void HandleKey(KeyRoutedEventArgs e)
  13. {
  14. switch (e.Key)
  15. {
  16. // allow digits
  17. // TODO: keypad numeric digits here
  18. case Windows.System.VirtualKey.Number0:
  19. case Windows.System.VirtualKey.Number1:
  20. case Windows.System.VirtualKey.Number2:
  21. case Windows.System.VirtualKey.Number3:
  22. case Windows.System.VirtualKey.Number4:
  23. case Windows.System.VirtualKey.Number5:
  24. case Windows.System.VirtualKey.Number6:
  25. case Windows.System.VirtualKey.Number7:
  26. case Windows.System.VirtualKey.Number8:
  27. case Windows.System.VirtualKey.Number9:
  28. e.Handled = false;
  29. break;
  30.  
  31. // only allow one decimal
  32. // TODO: handle deletion of decimal...
  33. case (Windows.System.VirtualKey)190: // decimal (next to comma)
  34. case Windows.System.VirtualKey.Decimal: // decimal on key pad
  35. e.Handled = (_hasDecimal == true);
  36. _hasDecimal = true;
  37. break;
  38.  
  39. // pass varIoUs control keys to base
  40. case Windows.System.VirtualKey.Up:
  41. case Windows.System.VirtualKey.Down:
  42. case Windows.System.VirtualKey.Left:
  43. case Windows.System.VirtualKey.Right:
  44. case Windows.System.VirtualKey.Delete:
  45. case Windows.System.VirtualKey.Back:
  46. case Windows.System.VirtualKey.Tab:
  47. e.Handled = false;
  48. break;
  49.  
  50. default:
  51. // default is to not pass key to base
  52. e.Handled = true;
  53. break;
  54. }
  55. }
  56. }

这是一些示例XAML.请注意,它假定MyNumericTextBox位于项目命名空间中.

  1. <StackPanel Background="Black">
  2. <!-- custom numeric textBox -->
  3. <local:MyNumericTextBox />
  4. <!-- normal textBox -->
  5. <TextBox />
  6. </StackPanel>

猜你在找的Windows相关文章