Jacob
Jacob

Reputation: 101

How to block space in passwordbox in wpf

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?

Upvotes: 1

Views: 460

Answers (2)

Hossein Ebrahimi
Hossein Ebrahimi

Reputation: 822

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).

Upvotes: 1

NEBEZ
NEBEZ

Reputation: 750

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;
    }

Upvotes: 4

Related Questions