What\'s the best way to catch the return key in a PasswordBox? (WPF/XAML)
I have a TextBox field and a PasswordBox field on my login form (for username and password en
There is an even easier mechanism to activate the button's code. WPF Button class provides a property called IsDefault. When set to true, if you press return while some objects in the window have focus, the code of the click event of the button will be fired automatically. This mechanism works like a charm with the passwordbox.
You could try using a RoutedCommand.
You can set it on the Command property of the Button.
You can also add a KeyGesture to the InputBindings of your loginform to bind the Enter key to trigger your RoutedCommand.
Then add a CommandBinding in the CommandBindings of your loginform to bind the RoutedCommand to Executed handlers in your code and perform or trigger your login validation process.
You can handle the KeyDown event on the PasswordBox (and TextBox if desired) and then use the following event handler --
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Return && e.Key != Key.Enter)
return;
e.Handled = true;
HandleEnter();
}