本文介绍了使用 UWP TextBox.TextChanging 忽略错误数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 UWP 应用程序,它具有不同的文本框来输入数字.为了确保只能输入数字,我使用了 TextChanging 事件.遗憾的是,我找不到有关如何详细使用 TextChanging 来忽略错误输入的任何文档.

I'm creating a UWP app which has different TextBoxes to enter numbers. To make sure only numbers can be entered I use the TextChanging event. Sadly I can't find any documentation on how to use TextChanging in detail to ignore wrong inputs.

一个 TextBox 的工作解决方案如下:

A working solution for one TextBox is the following:

string oldText;
private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    double temp;
    if (double.TryParse(sender.Text, out temp) || sender.Text == "")
        oldText = sender.Text;
    else
    {
        int pos = sender.SelectionStart - 1;
        sender.Text = oldText;
        sender.SelectionStart = pos;
    }
}

使用这个解决方案,我需要每个 TextBox 的 string oldText 以及每个 TextBox 的 TextChanging 函数或函数内的更多代码.

Using this solution I would need a string oldText for each TextBox and either also a TextChanging function for each of it or a lot more code inside the function.

是否有一种简单的方法可以忽略 TextBox.TextChanging 事件中的错误"输入?

Is there a easy way to ignore "wrong" inputs in the TextBox.TextChanging event?

推荐答案

在 Romasz 的第一条评论中的链接的帮助下,我想出了这个解决方案:

With the help of Romasz link in his first comment I came up with this solution:

private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    double dtemp;
    if (!double.TryParse(sender.Text, out dtemp) && sender.Text != "")
    {
        int pos = sender.SelectionStart - 1;
        sender.Text = sender.Text.Remove(pos, 1);
        sender.SelectionStart = pos;
    }
}

这很好用,除非选择了输入值的一部分,然后输入了错误的字符.

This works quite fine except when a part of the input value is selected and then a wrong character is entered.

我改进了上述版本以使用 Regex.所以现在我可以检查应该允许输入的任何内容:

I improved the above version to use Regex. So now I'm able to check whatever content should be allowed to enter:

private void tbInput_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;
    }
}

这篇关于使用 UWP TextBox.TextChanging 忽略错误数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 17:01