I'm building a form in a C# WinRT app, and I'd like to restrict the characters in one of the TextBox components to numerals only. (This TextBox would be for a user to enter a year into.)
I've searched for a while, but haven't been able to figure this one out without setting up an event listener on the TextChanged
event, and inspecting the text
property on every key press. Is there a way to simply say that a user can only enter specific characters into a TextBox?
Note − By default, we can enter data in a textarea upto 5,24,288 characters. In some cases, there is a need of putting a limit on the size of characters that can be typed in a textarea. So in that case, we can use maxlength attribute to control the number of characters entered in a textarea.
Use the MaxLength property to limit the number of characters that can be entered in the TextBox control. This property is applicable only when the TextMode property is set to TextBoxMode. SingleLine or TextBoxMode. Password .
How To: Use the Text Field. The Text field is one of the most generic and common data entry fields used to capture text type data—letters, numbers, and symbols. Text fields hold up to 255 characters in a single line.
The simplest thing that could possibly work is to bind to the OnTextChanged
event and modify the text according to your rules.
<TextBox x:Name="TheText" TextChanged="OnTextChanged" MaxLength="4"/>
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (TheText.Text.Length == 0) return;
var text = TheText.Text;
int result;
var isValid = int.TryParse(text, out result);
if (isValid) return;
TheText.Text = text.Remove(text.Length - 1);
TheText.SelectionStart = text.Length;
}
However, I'd shy away from this approach since the mantra of Metro is touch first UI and you can easy do it in a touch first manner with a FlipView
control.
Try setting TextBox.InputScope property to InputScopeNameValue.Number, as mentioned in Guidelines and checklist for text input in MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With