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?
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.
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 moreModifierKeys
.
Therefore, one modifier on its own cannot be used as a valid Gesture
in a KeyBinding
.
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.
Try setting IsMainMenu="True"
on your Menu
control. Does that give you the behavior you're looking for?
Try to set Modifiers="Alt"
and Key="LeftAlt"
:
<KeyBinding Key="LeftAlt" Modifiers="Alt" Command="{x:Static local:MainWindow.ShowMenuCommand}" />
精彩评论