Search code examples
c#xamlwindows-store-appswindows-8.1

Check if a character typed in a PasswordBox is numeric or not


I have researched a little and it seems that there is not InputScope for passwordboxes in xaml. I'm setting up a pin field and only want numbers. if figure i will need to check the if the key pressed is numeric in C# before it writes it to the box. how would i go about doing this? it will also be checking if the length is 4 so it can automatically login which i already know how to do.


Solution

  • You can subscribe for KeyDown event on the PasswordBox. Maxmum Length can be restricted by setting MaxLength property.

    private void OnKeyDown(object sender, KeyEventArgs e)
    {
        if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))          
        return;
    
        e.Handled = true;            
    }