我正试图在 Windows 8 tile 应用程序中找到 Numericbox 的一个很好的替代品。我尝试使用与 Windows 窗体相同的数字框,但收到一条错误消息,指出 Windows 8 应用程序不支持(?)这些。我注意到 tile 应用程序的 TextBox 元素有一个可以设置为“数字”的 InputScope,但它仍然允许用户输入他想要输入的任何字符。我假设 InputScope 没有按照我的想法行事。
我目前正在使用文本框进行管理,但是因为我在进行计算,所以文本必须不断地转换为十进制,然后在我想更新界面时再转换回文本,此外还必须执行多项检查以确保用户不输入非数字字符。这变得非常乏味,并且非常熟悉 Windows 窗体,这似乎是朝着错误方向迈出的一步。我一定是遗漏了一些明显的东西吗?
最佳答案
我不熟悉 NumericTextBox
,但这是一个简单的 C#/XAML 实现,它只允许数字和小数点字符。
它所做的只是覆盖 OnKeyDown
事件;根据按下的键,它允许或不允许事件到达基础 TextBox
类。
我应该指出,此实现是针对 Windows 应用商店应用的 - 我相信您的问题是关于这种类型的应用,但我不是 100% 确定。
public class MyNumericTextBox : TextBox
{
protected override void OnKeyDown(KeyRoutedEventArgs e)
{
HandleKey(e);
if (!e.Handled)
base.OnKeyDown(e);
}
bool _hasDecimal = false;
private void HandleKey(KeyRoutedEventArgs e)
{
switch (e.Key)
{
// allow digits
// TODO: keypad numeric digits here
case Windows.System.VirtualKey.Number0:
case Windows.System.VirtualKey.Number1:
case Windows.System.VirtualKey.Number2:
case Windows.System.VirtualKey.Number3:
case Windows.System.VirtualKey.Number4:
case Windows.System.VirtualKey.Number5:
case Windows.System.VirtualKey.Number6:
case Windows.System.VirtualKey.Number7:
case Windows.System.VirtualKey.Number8:
case Windows.System.VirtualKey.Number9:
e.Handled = false;
break;
// only allow one decimal
// TODO: handle deletion of decimal...
case (Windows.System.VirtualKey)190: // decimal (next to comma)
case Windows.System.VirtualKey.Decimal: // decimal on key pad
e.Handled = (_hasDecimal == true);
_hasDecimal = true;
break;
// pass various control keys to base
case Windows.System.VirtualKey.Up:
case Windows.System.VirtualKey.Down:
case Windows.System.VirtualKey.Left:
case Windows.System.VirtualKey.Right:
case Windows.System.VirtualKey.Delete:
case Windows.System.VirtualKey.Back:
case Windows.System.VirtualKey.Tab:
e.Handled = false;
break;
default:
// default is to not pass key to base
e.Handled = true;
break;
}
}
}
这是一些示例 XAML。请注意,它假定 MyNumericTextBox
在项目命名空间中。
<StackPanel Background="Black">
<!-- custom numeric textbox -->
<local:MyNumericTextBox />
<!-- normal textbox -->
<TextBox />
</StackPanel>
关于windows - Windows 8 应用程序中 Numericbox 的替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13240442/