TextBoxcontrol in UWP supports any textual input from the user, but in some cases, you might prefer to allow only plain numbers. In this article, I will show two different approaches which will allow you to do just that.
Preventing non-digit input
If we want to make sure no non-digit character can be entered in the
TextBox we can use the
|<TextBox BeforeTextChanging="TextBox_OnBeforeTextChanging" />|
In the handler, we can use simple LINQ query to check if the input consists only of digits. In case we encounter any non-digit character we simply cancel the text change.
|private void TextBox_OnBeforeTextChanging(TextBox sender,|
|args.Cancel = args.NewText.Any(c => !char.IsDigit(c));|
Filtering non-digit input
When the TextChanging event occurs, the Text property already reflects the new value (but it’s not rendered in the UI). You typically handle this event to update the Text value and selection before the text is rendered. This prevents the text flickering that can happen when text is rendered, updated, and re-rendered rapidly.
|<TextBox TextChanging="TextBox_OnTextChanging" />|
And the event handler will again use LINQ to make the whole logic very clear and simple. We take all the newly updated
Text property value and filter it to digits only.
|private void TextBox_OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)|
|sender.Text = new String(sender.Text.Where(char.IsDigit).ToArray());|
Note: Both presented solutions work for simple, digit-only numeric input. They can be extended to support more general numeric input like decimals or to allow for separators between thousands. However, each culture has its own formatting rules, so it is usually more appropriate to set the
TextBox.InputScope property to an appropriate value and then perform additional validation in code, using .NET built-in
TryParse methods which can handle culture-specific formatting.