jamier
jamier

Reputation: 832

Keybinding in WPF

I'm new to WPF and in an application i'm building I'd like to show the main menu when the alt key is pressed just like windows explorer in vista and windows 7. I've tried using a keybinding with just the modifier set but that doesn't seem to work.

Heres by code so far:

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:MainWindow.ShowMenuCommand}"
                        CanExecute="ShowMenuCommand_CanExecute"
                        Executed="ShowMenuCommand_Executed"/>
</Window.CommandBindings>
<Window.InputBindings>
    <KeyBinding Key="Alt" Command="{x:Static local:MainWindow.ShowMenuCommand}" />
</Window.InputBindings>

I'd also like the menu to disappear when the focus is lost.

Any ideas?

Upvotes: 4

Views: 10118

Answers (5)

Sheridan
Sheridan

Reputation: 69959

Disclaimer: This is not an attempt at an answer as the user has already found a solution. This is just to provide additional information on the subject.

For anyone that wants to know why @jamier's attempt at this KeyBinding doesn't work, the answer can be found in the KeyBinding Class page on MSDN:

With the exception of the function keys and the numeric keypad keys, a valid KeyGesture must contain exactly one Key and one or more ModifierKeys.

Therefore, one modifier on its own cannot be used as a valid Gesture in a KeyBinding.

Upvotes: 2

Marcus L
Marcus L

Reputation: 4080

Try to set Modifiers="Alt" and Key="LeftAlt":

<KeyBinding Key="LeftAlt" Modifiers="Alt" Command="{x:Static local:MainWindow.ShowMenuCommand}" /> 

Upvotes: 0

casperOne
casperOne

Reputation: 74530

Have you tried setting the Key attribute to "LeftAlt" or "RightAlt"? The Key attribute is of type System.Windows.Input.Key enumeration, which doesn't have an "Alt" value.

Alt is used as a modifier in a KeyGesture, so that is why you see it separately in other places. However, in the Key enumeration, it specifically has instances for the left and right Alt keys.

You will more than likely have to have two bindings, one for each alt key.

Upvotes: 1

John Bowen
John Bowen

Reputation: 24453

Try setting IsMainMenu="True" on your Menu control. Does that give you the behavior you're looking for?

Upvotes: 0

jamier
jamier

Reputation: 832

The answer I was looking for can be found here:

http://www.stackoverflow.com/questions/1218394/how-can-i-toggle-the-main-menu-visibility-using-the-alt-key-in-wpf

Thanks to everyone for the help.

Upvotes: 2

Related Questions