Windows 8应用程序中Numericbox的替代方案是什么?

8
我正在寻找一个适用于Windows 8平铺应用的好替代Numericbox控件。我尝试使用现有于Windows窗体中的Numericbox控件,但是出现了一个错误,说这些控件不被Windows 8应用程序支持(?)。我注意到Tile应用程序的TextBox元素有一个InputScope属性,可以设置为"Number",但它仍然允许用户输入任何字符。我猜InputScope并没有起到我想象中的作用。
我目前使用TextBox控件来处理问题,但是因为我需要进行计算,每次更新界面时都必须将文本转换为十进制数,然后再转回文本,此外还要执行多个检查,以确保用户不输入非数字字符。这变得非常乏味,和我的Windows Form非常熟悉相比,这似乎是朝着错误方向迈出的一步。我一定是漏掉了什么明显的东西?

InputScope 用于触摸输入键盘类型。 - BrunoLM
2个回答

3
我不熟悉 NumericTextBox,但这里有一个简单的 C#/XAML 实现,只允许数字和小数点。
它所做的就是重写 OnKeyDown 事件;根据按下的键,它要么允许要么禁止事件到达基本的 TextBox 类。
我应该指出,这个实现是为 Windows Store 应用程序设计的 - 我相信你的问题是关于这种类型的应用程序,但我不确定。
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>

仅供参考,此示例不适用于Shift +数字,因此允许特殊字符通过,另外小数点只能添加一次,如果删除则无法再次添加。 - Dave

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接