【问题标题】:Binding command in viewmodel to menuitem and short cut key [duplicate]将视图模型中的命令绑定到菜单项和快捷键[重复]
【发布时间】:2016-06-18 22:54:00
【问题描述】:

我正在使用 MVVM Light 构建一个小型 WPF 应用程序,这是我使用此框架的第一个应用程序。

我的MainViewModel 中有许多命令:

public RelayCommand NewCommand { get; private set; }
public RelayCommand OpenCommand { get; private set; }
// etc.

public MainViewModel() {
    NewCommand = new RelayCommand( CreateNewFile, CanCreateNewFile );
    OpenCommand = new RelayCommand( OpenFile, CanOpenFile);
    // etc.
}

在我的 XAML 中,我有一个菜单:

<DocPanel>
    <Menu Name="MainMenu">
        <MenuItem Header="File">
            <MenuItem Header="New" Command="{Binding NewCommand}" />
            <MenuItem Header="Open" Command="{Binding OpenCommand}" />
            <!-- etc. -->
        </MenuItem>
    <Menu>
</DocPanel>

一切顺利。但是如何将这些命令绑定到常用的键盘快捷键,例如 Ctrl-N 用于新命令,Ctrl-O 用于打开命令等?

【问题讨论】:

    标签: c# wpf mvvm data-binding mvvm-light


    【解决方案1】:

    将 InputBinding 添加到 Window 的 InputBindings 中。

    private MainViewModel m_ViewModel = new MainViewModel();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = m_ViewModel;
    
        var keyGesture = new KeyGesture(Key.N, ModifierKeys.Control);
        var keyBinding = new KeyBinding(m_ViewModel.NewCommand, keyGesture);
        this.InputBindings.Add(keyBinding);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-29
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 2014-11-08
      相关资源
      最近更新 更多