Using UWP TextBox.TextChanging to ignore invalid data

I am creating a UWP application that has different text fields for entering numbers. To make sure that only numbers are entered, I use the TextChanging event. Unfortunately, I cannot find documentation on how to use TextChanging in detail to ignore incorrect inputs.

The working solution for a single TextBox is as follows:

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 will need a string oldText for each TextBox, as well as a TextChanging function for each of them, or much more code inside the function.

Is there an easy way to ignore the β€œwrong” inputs in the TextBox.TextChanging event?

+5
source share
2 answers

Using the Romasz link in my 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 fine if you don’t select part of the input value and then enter the wrong character.

Edit: I used an improved version to use Regex. So, now I can check what 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; } } 
+9
source

Try using the PreviewTextInput event that passes TextCompositionEventArgs, which has a Handled property that can be used when routing the event to pause the base control implementation by setting Handled = true.

0
source

Source: https://habr.com/ru/post/1242234/


All Articles