本文介绍了使用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;
    }
}



使用这个解决方案,我需要一个字符串oldText 每个文本框,要么还为每个它,或者在函数中有更多的代码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.

编辑:
我改进了以上版本使用正则表达式。所以,现在我可以检查什么内容应该被允许进入:

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