Number-only TextBox in UWP

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.

https://gist.github.com/MartinZikmund/191894c174031be996f874f7284facf0

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.

https://gist.github.com/MartinZikmund/712452513468379a0cf9a4c3e00206a1

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.

https://gist.github.com/MartinZikmund/0120e49e7b42f0da425af2ad349e5dd2

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.

https://gist.github.com/MartinZikmund/b525954405a5d842a555040fa6c9d0c7

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.

Buy me a coffeeBuy me a coffee

1 thought on “Number-only TextBox in UWP”

  1. I let the user type whatever she wants but I have validation rules and styling to let her know when something is wrong. Indeed, in my experience users don’t like when you ignore what they type.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.