Search code examples
c#wpfmvvmrelaycommand

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


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?


Solution

  • 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.