How to block space in passwordbox in wpf

397 Views Asked by At

I’m using a PasswordBox control in wpf.

I want to block space in the control, but i can’t find the way. I tried to use a KeyDown event but the event isn’t working.

What is the best way to block space in the PasswordBox?

2

There are 2 best solutions below

2
On BEST ANSWER

For WPF you should using PreviewKeyDown Based on docs occurs before the KeyDown event When a key is pressed while focus is on this control.

XAML:

<PasswordBox x:name="txtPasscode" PreviewKeyDown="txtPasscode_PreviewKeyDown"/>

and in behind :

private void txtPasscode_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space && txtPasscode.IsFocused == true)
            {
                e.Handled = true;
            }
        }

Also in C# native try this :

 private void txtPasscode_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == ' ') e.Handled = true;
    }
0
On

The KeyDown event you're handling actually fires after the character added to the passwordbox. You can block it by handling PreviewKeyDown this way(KeyDown won't fire anymore if user pressed space):

private void passwordbox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        e.Handled = true;
    }
}

If you need to block an event you're going to use the event beginning with "Preview"(read more here).