如何将应用程序命令绑定到视图模型(WPF)?

时间:2011-05-18 17:17:16

标签: c# wpf mvvm relaycommand

我已经阅读过Josh Smiths关于使用RelayCommand查看模型的绑定命令的文章。但是,我需要将ApplicationCommands.Save绑定到视图模型,以便当用户单击保存菜单项时,它将在窗口中处理。怎么可能?

5 个答案:

答案 0 :(得分:1)

我知道我们使用服务的最佳解决方案。例如,像这样的ICommandBindingsProvider:

public interface ICommandBindingsProvider
{
    CommandBindingCollection CommandBindings { get; }
}

这会被注入您的ViewModel并像这样使用:

public MyViewModel(ICommandBindingsProvider commandBindings)
{
    commandBindings.Add(new CommandBinding(....));
}

如何注入服务将取决于您正在使用的MVVM框架。大多数(但不是全部)支持某种服务注入功能。如果您需要一个更具体的代码示例,请查看执行服务注入的Onyx并拥有可以执行此操作的服务。

答案 1 :(得分:1)

good tutorial来帮助绑定应用程序命令。

  1. 为视图设置命令绑定集合以在视图模型中绑定。 e.g:
  2. public CommandBindingCollection CommandBindings { get; }
    
    public YourViewModel()
    {
    //Create a command binding for the save command
    var saveBinding = new CommandBinding(ApplicationCommands.Save, SaveExecuted, SaveCanExecute);
    
    //Register the binding to the class
    CommandManager.RegisterClassCommandBinding(typeof(YourViewModel), saveBinding);
    
    //Adds the binding to the CommandBindingCollection
    CommandBindings.Add(saveBinding);
    }
    
    1. 设置附加属性。请阅读the article了解如何操作。

    2. 然后使用附加属性绑定到它。

    3. <UserControl local:AttachedProperties.RegisterCommandBindings="{Binding CommandBindings}"> 
          <Window.DataContext>
              <local:YourViewModel></local:YourViewModel>
          </Window.DataContext>
      </UserControl>
      

答案 2 :(得分:0)

您的保存菜单项是如何创建的?它某处必须绑定到ApplicationCommands.Save?您可以更改它,以便它与ViewModel的保存绑定。

答案 3 :(得分:0)

或者,将save命令绑定放在viewmodel上,然后将数据绑定到它,类似于(伪代码)

在viewmodel中:

...
public Command SaveCommand { get { return yourCodeHere; } }
...

在视图中:

<Button Command="{Binding Path=SaveCommand}" Content="Click"/>    

更新:我刚尝试绑定到命令绑定中的命令,但它不起作用。 我在想的是绑定到命令

答案 4 :(得分:0)

我过去成功使用过这种方法:

首先在ViewModels上定义一个CommandBindings属性(与Views相同的定义)。

然后,对于ViewModel实现的每个Command,将CommandBinding添加到ViewModel的CommandBindings。

然后,当你设置:

view.DataSource = viewModel;

同时设置:

view.CommandBindings.AddRange(viewModel.CommandBindings);

我认为可以使用CommandBindings属性的绑定来完成(无法确定)。