如何仅在 TextBox 中注册数字?(我没有 KeyPress 事件) [英] How can I register only numbers in TextBox?(i dont have KeyPress event)

查看:19
本文介绍了如何仅在 TextBox 中注册数字?(我没有 KeyPress 事件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图只允许在 TextBox、C# UWP XAML 中注册数字我没有 KeyPress 事件,我该怎么办?

I am trying to allow to register only numbers in TextBox, C# UWP XAML and i dont have the KeyPress Event what should i do?

与我想要做的等效的 WinForms 是这样的:

The WinForms equivalent of what I want to do is this:

private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) 
    {
        e.Handled = true;
    }
}

推荐答案

您可以使用 KeyDownKeyUp 事件.我在 Windows 10 操作系统上的 UWP 应用上测试了这段代码.工作正常.

You can use KeyDown and KeyUp events. I tested this code on UWP app on Windows 10 OS. Working fine.

<TextBox InputScope="NumberFullWidth" KeyDown="TextBox_KeyDown"></TextBox>

InputScope 将在触摸设备上打开特定设备的键盘.

InputScope will open specific device keyboard on touch device.

private void TextBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
    if (e.Key.ToString().Equals("Back"))
    {
        e.Handled = false;
        return;
    }
    for (int i = 0; i < 10; i++)
    {
        if (e.Key.ToString() == string.Format("Number{0}", i))
        {
            e.Handled = false;
            return;
        }
    }
    e.Handled = true;
}

PS:您需要更改此代码以支持带小数点的数字和任何其他字符(如果要支持).

PS: You need to change this code to support numbers with decimal points and any other characters (if want to support).

这篇关于如何仅在 TextBox 中注册数字?(我没有 KeyPress 事件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆