Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - Using UWP TextBox.TextChanging to ignore wrong data

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.

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;
    }
}

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Edit: 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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...