将ICommand绑定到MenuItem并指定ShortCut

时间:2017-08-17 09:03:20

标签: c# wpf icommand

我有以下情况:

具有多个ICommand(RelayCommand)属性的ViewModel。这些属性绑定到视图中的菜单项。一些菜单项应该有键盘快捷键。为此,我尝试使用窗口的InputBindings。这有效 - 但我必须手动将InputGestureText分配给MenuItem。所以我想有一种更好的方法将ICommand绑定到MenuItem并分配一个快捷方式......

// ViewModel
class MyViewModel: ViewModelBase {
    public ICommand TestCommand {get; set;}
}

// View
<Window...>

    <Window.InputBindings>
        <KeyBinding Command="{Binding TestCommand}" Key="R" Modifiers="Control" />
    </Window.InputBindings>

    // ...
    <MenuItem Name="MenuItemTest" Command="{Binding TestCommand}"
              Header="Test" InputGestureText="Ctrl + R" />

</Window>

2 个答案:

答案 0 :(得分:2)

var transactionValues; request("/rest/transactions/" + walletId, "GET").done(function (transactions) { // we have the data with is in the form of ResponseEntity<List<String>> $.each(transactions, function (transaction) { transactionValues += transaction.toString() + "</br>"; }); $("#transactions").text(transactionValues); }); 属性仅用于设置描述输入手势的文本,该手势将调用与命令关联的命令。

以某种方式将输入手势与菜单项相关联;它只是将文本添加到菜单项。这在MSDN上有记录:https://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.inputgesturetext(v=vs.110).aspx

所以不,没有更好的办法来做你正在做的事情:)

答案 1 :(得分:0)

May be I am a bit late, but:

Automatic shortcut hinting on menu items works with RoutedCommand.

public static readonly RoutedUICommand NewProject = new RoutedUICommand() { InputGestures = { new KeyGesture(Key.N, ModifierKeys.Control) } };

If you do so - you will get your hotkey working (even without input binding in window) and you will see this hotkey in any menu item bound to this command. This will work only with RoutedCommand (type is hardcoded in WPF source). If your command is not RoutedCommand (and it isn't, as you use ICommand pattern) - you have to set gesture hints by your own.

So there are two options: use RoutedCommand and event handlers for them (in UI code!) or implement your own commands and do whatever you can with shortcut hints.

相关问题