Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 916
Jimmy Avatar asked May 18 '11 17:05

Jimmy


2 Answers

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.

like image 108
wekempf Avatar answered Nov 03 '22 07:11

wekempf


There is a good tutorial to help bind application commands.

  1. Setup your command binding collection for your view to bind to in your view model. e.g.:
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. Setup attached properties. Read the article on how to do that.

  2. Then bind to it using attached properties.

<UserControl local:AttachedProperties.RegisterCommandBindings="{Binding CommandBindings}"> 
    <Window.DataContext>
        <local:YourViewModel></local:YourViewModel>
    </Window.DataContext>
</UserControl>
like image 30
Seth Avatar answered Nov 03 '22 08:11

Seth