Number-only TextBox in UWP

WinUI XAML

5 years ago

The built-in TextBox control 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 BeforeTextChanging event.

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.

Filtering non-digit input

Instead of preventing non-digit input, we can instead just filter out the non-digit characters. In this case we can use the TextChanging event, which is exactly suited for this scenario, as docs say:

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.

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.

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.