如何绑定应用程序命令以查看模型(WPF)?

问题描述:

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

I have already read Josh Smiths article about binding commands to view model using RelayCommand. However I need to bind ApplicationCommands.Save to a view model so that when a user clicks the save menu item it is handled in the window. How is it possible?

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

The best solution I'm aware of us to use a service. For example, an ICommandBindingsProvider like this:

public interface ICommandBindingsProvider
{
    CommandBindingCollection CommandBindings { get; }
}

这将注入到您的ViewModel中,并按如下方式使用:

This gets injected into your ViewModel and used like this:

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

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

How the service gets injected will be dependent on what MVVM framework you're using. Most (but not all) support some sort of service injection capabilities. If you need a more concrete code example, look at Onyx which does service injection and has a service that does just this.