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.

<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,
TextBoxBeforeTextChangingEventArgs args)
args.Cancel = args.NewText.Any(c => !char.IsDigit(c));

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.

<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.

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.