文本框的输入范围在 windows 10 个通用应用程序中不起作用

Input scope for textbox not working in windows 10 universal apps

这里我试了一下代码。

Xaml:

<TextBox Header="Telephone Number" InputScope="TelephoneNumber"/>

CS:

TextBox phoneNumberTextBox = new TextBox();
phoneNumberTextBox.Header="Telephone Number";    
InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName();
scopeName.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(scopeName);
phoneNumberTextBox.InputScope = scope;

但是当我按下键盘上的任意键时,它会在文本框中显示任何人请帮助我..

阅读文档https://msdn.microsoft.com/library/windows/apps/hh702632

The input scope provides a hint at the type of text input expected by the control. Various elements of the system can respond to the hint provided by the input scope and provide a specialized UI for the input type. For example, the touch keyboard might show a number pad for text input when the control has its InputScope set to Number.

The control might also interpret the data being entered differently (typically for East Asian related input scopes). The input scope does not perform any validation, and does not prevent the user from providing any input through a hardware keyboard or other input device.

如果你想限制来自文本框的字符尝试在文本框内添加Key_Down事件。

<TextBox Name="textbox" KeyDown="textbox_KeyDown" MaxLength="10"InputScope="Number" />

和 C# 代码

 private void textbox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if ((e.Key < VirtualKey.NumberPad0 || e.Key > VirtualKey.NumberPad9) & (e.Key < VirtualKey.Number0 || e.Key > VirtualKey.Number9))
        {
            e.Handled = true;
        }
    }

这是我的解决方案

<TextBox Name="texbox"   TextChanging="intTextBox_TextChanging" MaxLength="10" InputScope="Number" />


private void intTextBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    if (!Regex.IsMatch(sender.Text, "^\d*?\d*$") && sender.Text != "")
    {
        int pos = sender.SelectionStart - 1;
        sender.Text = sender.Text.Remove(pos, 1);
        sender.SelectionStart = pos;
    }
}