Windows 8 : How to only type numbers in a Textbox ? C#/XAML

I want a Textbox where a user can only type numbers, for example for a quantity. I thought that would be easy but nothing is already implemented for that. So here is my way to do it !

First, you can force the tablet to open the numeric keyboard when the user selects the textbox with the InputScope property :

<TextBox x:Name="Textbox_Quantity"
InputScope="Number"/>

Then I tried to block a letter when the user type it with the Keydown event and It worked until I realize the Key property is not dealing with capslock. Indeed, the KeyRoutedEventArgs returns « Number3 » when I type on « 3 » but the same key is also  » or # when there’s no capslock.

private void tbNumber_OnKeyDown(object sender, KeyRoutedEventArgs e)
{
char c = Convert.ToChar(e.Key);
e.Handled = !Char.IsNumber(c) ; //not working with everything !
}

Finally, I choose to deal with the TextChanged event. Because the user can enter a letter at any position of the Textbox, you can’t only proccess the last character of the string. So, you have to verify each letter one by one to find which one is not a number. Here is my code, if you did it with another method, share it in the comments ! 🙂

<TextBox x:Name="Textbox_Quantity"
InputScope="Number"
TextChanged="Textbox_Quantite_OnTextChanged" />

 

private void TextboxQuantity_OnTextChanged(object sender, TextChangedEventArgs e)
{
var finalValue = "";
var myTextBox = sender as TextBox;
if (myTextBox != null)
{
var newValue = myTextBox.Text;
var textArray = newValue.ToCharArray();

foreach (char letter in textArray)
{
if (Char.IsNumber(letter)) finalValue = finalValue.Insert(finalValue.Length, letter.ToString());
}
myTextBox.Text = finalValue;
myTextBox.SelectionStart = finalValue.Length;
}
}

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *