Implementing ICommand in your Silverlight 4 project only requires a few steps. I have had a dozens of questions about this lately so I decided to share a very simple technique to implement commanding in Silverlight 4.
Step 1 – Implement ICommand
The first step is to implement the ICommand interface with a class that will manage the commanding aspects. There are other options to do this, but here is a simplified yet powerful implementation of ICommand.
The DelegatedCommand class implements ICommand’s CanExecute method, the Execute method, and the CaneExecuteChanged event. This code can be copied and used “as is”.
Step 2 – Define the Command
Add a public property to your ViewModel to represent the ICommand. This property will be bound to your View through a button, generally.
Step 3 – Create the Command
In the constructor of your ViewModel, set the command property you created in step 1.
Step 4 – Create the VM
You must then make sure your ViewModel is accessible in your View. This is can be done in many ways. But for simplicity I am showing the ViewModel created as a static resource in the View’s XAML.
Step 5 – Bind the Command
Add a button control and bind the Command property to the command you created in the ViewModel. Then if you need to pass a parameter into the command you can bind the CommandParameter property to an element in the View. I find that I generally do not need to pass a parameter in, but I added this here as an example.
That’s it! 5 simple steps and now you have commanding in your application.
Want More …
I included the key code files in the post, below. No need to dive into them unless you want to grab the code as a starting point.
The complete ProductViewModel code can be seen here:
Here is the ViewModelBase class. It simply contains the FirePropertyChanged event that all ViewModel classes will use in my project.