How to bind application commands to view model(WPF)?

Jimmy picture Jimmy · May 18, 2011 · Viewed 7.9k times · Source

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?

Answer

wekempf picture wekempf · May 18, 2011

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

public interface ICommandBindingsProvider
{
    CommandBindingCollection CommandBindings { get; }
}

This gets injected into your ViewModel and used like this:

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

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.