您的位置:首页 > 其它

WPF菜单快捷方式怎么设置

2013-01-30 11:04 274 查看
参考:http://stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf

参考:http://stackoverflow.com/questions/4682915/defining-menuitem-shortcuts

You need to use
KeyBindings
(and
CommandBindings
if
you (re)use
RoutedCommands
such as those found in the
ApplicationCommands
class
)
for that inthe controls where the shortcuts should work.

e.g.

<Window.CommandBindings>

<CommandBinding Command="New" Executed="CommandBinding_Executed" />

</Window.CommandBindings>

<Window.InputBindings>

<KeyBinding Key="N" Modifiers="Control" Command="New"/>

</Window.InputBindings>


For custom
RoutedCommands
:

static class CustomCommands

{

public static RoutedCommand DoStuff = new RoutedCommand();

}

usage:

<Window

...

xmlns:local="clr-namespace:MyNamespace">

<Window.CommandBindings>

<CommandBinding Command="local:CustomCommands.DoStuff" Executed="DoStuff_Executed" />

</Window.CommandBindings>

<Window.InputBindings>

<KeyBinding Key="D" Modifiers="Control" Command="local:CustomCommands.DoStuff"/>

</Window.InputBindings>

...

</Window>

(It is often more convenient to implement the
ICommand
interface
rather
than using
RoutedCommands
. You canhave a constructor which takes delegates for
Execute
and
CanExecute
to easily create commands which do different things, suchimplementations are often called
DelegateCommand
or
RelayCommand
.
This wayyou do not need
CommandBindings
.)

MenuItem上显示快捷键:

<MenuItemHeader="{x:Static Prop:Resources.File_AddBookItemHeader}" InputGestureText="Ctrl+N"Command="local:CustomCommands.DoStuff" Foreground="Black"/>

也可以不用再xaml中声明keyBinding,而用代码:

static classCustomCommands

{

public staticRoutedCommand DoStuff = new RoutedCommand();

staticCustomCommands()

{

DoStuff.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: