WPF菜單快捷方式怎麼設置

參考: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 orRelayCommand. 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));

        }

    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章