Reputation: 4080
Is there a way to use KeyBinding
and execute the command on OnKeyUp in XAML?
If I want to bind the left-ALT key to execute my own command for menu access, because KeyBinding executes commands on OnKeyDown, I get some unwanted behaviour. For example, when tabbing out of the application with Alt+Tab
the command will fire, and if the key is held down, the command is retriggered until the key is released.
I know the ALT is a modifier key, and a bit of a special case, but by waiting for OnKeyUp these problems would be avoided.
Upvotes: 1
Views: 2126
Reputation: 132548
I typically use this Attached Command Behavior for hooking up Commands to Events
In your special case where you want to only execute the command when a specific key combination is pressed, I'd suggest hooking up both the KeyUp
event and the KeyUp
attached command.
In the regular KeyUp
event, check if the key combination you want is being pressed and if not, mark the event as Handled
so it doesn't get processed by the command as well
For example, this will only execute the bound command if the A key is pressed
<TextBox acb:CommandBehavior.Command="{Binding TestCommand}"
acb:CommandBehavior.Event="KeyUp"
KeyUp="TextBox_KeyUp"/>
and
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.A)
e.Handled = true;
}
Upvotes: 2