Search code examples
xamluwppasswordbox

UWP Xaml Password box allow only numbers


I want to add a passwordbox to my UWP app(Mainly use as a desktop application) which allows only numbers how can I achive this?

enter image description here


Solution

  • I have found a way to achive this.

    Xaml:

                    <PasswordBox
                    x:Name="ConfirmPinNumber"
                    Grid.Row="2"
                    Grid.Column="1"
                    Width="100"
                    Height="38"
                    Padding="10,8,10,0"
                    HorizontalAlignment="Left"
                    IsPasswordRevealButtonEnabled="False"
                    KeyDown="PasswordBox_KeyUp"
                    MaxLength="8"
                    PasswordRevealMode="Hidden" />
    

    Xaml.cs:

     private void PasswordBox_KeyUp(object sender, KeyRoutedEventArgs e)
        {
            if (Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down) ||
                !(e.Key >= VirtualKey.Number0 && e.Key <= VirtualKey.Number9 || e.Key >= VirtualKey.NumberPad0 && e.Key <= VirtualKey.NumberPad9 || e.Key == VirtualKey.Enter))
            {
                e.Handled = true;
                return;
            }
        }
    

    Trying to add special characters using shift key and number keys handle from the below code.

    Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down)