In a MVVM application actions in the view trigger the logic in the view model through the use of commands.Command is a class implementing the ICommand interface.ViewModel can implement commands for every action in the view.View can then bind and trigger these commands for different actions on the UI.
Though command objects created using ICommnd interface solves the problem of tigh coupling between action invoker and action logic,it is tedious process to create command for every action.
- You need to implement the ICommnd interface.
- declare properties for these ICommand implementations
- create objects for ICommand implementations and assign to properties.
Delegate command provides a prebuilt ICommnd implementation.So in ViewModel we can directly create objects of Delegate command.When creating an object of Delegate command execute and canexecute methods can be specified.
It is part of the PRISM library.To use delegate command you need to reference the following namespace:
Microsoft.Practices.Prism.Commands
DelegateCommand class inherits from the class DelegateCommandBase which is in the Microsoft.Practices.Prism.Commands namespace.
So when you create a viewmodel you can simply declare the Delegate command as:
class SimpleViewModel{ string message; private DelegateCommand simpleCommand; public DelegateCommand SimpleCommand { get { return simpleCommand; } } }
and then create object of Delegate command and assign it to the SimpleCommand property:
SimpleCommand = new DelegateCommand(simpleMethod, canExecuteSimpleMethod); private void simpleMethod() { message="Hello World"; } private bool canExecuteSimpleMethod() { return true; }
Leave a Reply