I have not worked with WPF for a while. Recently, I need to make enhancement to a WPF project that I did 20 months ago. It is time to refresh my memory on several WPF unique things. The first thing that came to my mind is WPF Commanding.
In the old days when we create a VB 1-6 or Windows Forms applications, we just double click a button from the designer to create an event handler. With WPF, we can still do it the old way but there is a new way: we bind the Command property of the control to a property of the view model that implements ICommand. So what is ICommand?
The ICommand interface has 3 members: Execute, CanExecute and CanExecuteChanged.
Why the complications? That is because the WPF Commanding allows enable/disable the command sources such as button and menu item without resorting to spaghetti code.The basic workflow is simple:
- Whenever we change a state in the view model that we think that might affect CanExecute state of the command, we call the this.MyCommand.CanExecuteChanged() method.
- This will trigger the view to call the CanExecute method the command object to determine whether the command source should be enabled.
- When the command source is enabled and clicked, the Execute method of the command object is called; there is where the event handler would be implemented.
The prism project has a nice implementation of ICommand called DelegateCommand. Its declaration is fairly simple:
All we need is to instantiate it and give it a executeMethod call back and an optionally canExecuteMethod call back.
Noticed that both CanExecute and Execute functions allow one argument? We could use the mechanism to bind multiple controls to a single command on the view model. We can use CommandParameter of the control to differentiate the controls.