MVVM – Using commands
MVVM – Using commands
On my previous post I’ve talked about MVVM in general. I’ve also
demonstrated how data binding with ViewModel works.
There is, however, issue with buttons: Buttons won’t cause
property changes (like TextBox, ComboBox etc. where
you can have TwoWay binding mode) and therefor we cannot
cause the ViewModel to run code through property setters.
So, what do we do?
On non-MVVM scenario we will simply create an EventHandler
on our code-behind and attach it to our Click event . However,
now we want to keep our code-behind as clean as possible.
In this post, I’ll demonstrate how to do so, using the button’s
Commnand property.
The button’s Command property type is ICommand , you can
implement this interface yourselves, however there
is an implementation of class called RelayCommand
on MVVM light toolkit you can use. binding your button’s
command property will cause the ViewModel to run method
when your button is clicked.
How to bind button to command:
1. On your ViewModel create a property with type that
implements ICommand .
public ICommand ButtonPressed { get; set; }
2. Now, on your View-Model constructor, initialize your command property
so it’s Execute method will run a method on your View-Model class. On
RelayCommand it should look like that:
ButtonPressed = new RelayCommand(ButtonPressedMethod);
Where ButtonPressedMethod is the method to be run when button clicked.
(Kind of replacing your EventHandler for click event when used code-behind)
3. Now, Bind on your View .xaml file, your button to the command:
<Button Command="{Binding Path=ButtonPressed}"…
Well, That’s it…
Summary
In order to simply execute code when button is clicked we use Command property.
Command is silverlight button’s property, typed ICommand that has an Execute
method. This method should cause the execution of our code. If we implement the
interface we have to take care that the Execute command will run our code, Using
MVVM’s RelayCommand we can simply send our method as a parameter to the
command’s constructor.
You can download demo Here