Update: this blog has been moved to http://brandonzeider.me/2010/microsoft-net/silverlight-commanding-using-icommand/
Silverlight 4 adds a great new feature that was missing in Silverlight (but present in WPF): commanding. With commanding, implementing the Model-View-ViewModel (MVVM) pattern becomes much easier.
To use commanding in your Silverlight application, you must create a command object that implements the ICommand interface. ICommand is a simple interface, containing a CanExecute method, an Execute method, and a CanExecuteChanged event. Here is an example of a simple implementation:
using System;
using System.Windows.Input;
namespace Framework
{
public sealed class Command : ICommand
{
#region Fields
private readonly Action<object> _executeDelegate = null;
private readonly Func<object, bool> _canExecuteDelegate = null;
#endregion Fields
#region Constructors
public Command(Func<object, bool> canExecuteDelegate, Action<object> executeDelegate)
{
_executeDelegate = executeDelegate;
_canExecuteDelegate = canExecuteDelegate;
}
#endregion Constructors
#region ICommand Members
public bool CanExecute(object parameter)
{
if (_canExecuteDelegate == null)
{
return true;
}
else
{
return _canExecuteDelegate(parameter);
}
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (_executeDelegate != null)
{
_executeDelegate(parameter);
}
if (CanExecuteChanged != null)
{
CanExecuteChanged.Invoke(this, new EventArgs());
}
}
#endregion ICommand Members
}
}
Now you can add a property to your ViewModel that exposes an instance of this command.
public ICommand ButtonClickCommand { get { return new Command(ButtonClickValidator, ButtonClick); } }
Next you can add a control to your view that binds to this command. At the time this post was written, ICommand is only supported in controls deriving from ButtonBase. Bind the Command property to your command. You can also bind the CommandParameter property if you need to pass a value to your command.
<Button
Width="100"
Height="25"
Content="Click Me!"
Command="{Binding Path=ButtonClickCommand}"
CommandParameter="{Binding ElementName=InputTextBox, Path=Text}"/>
For an overview of the Model-View-ViewModel pattern, visit this great blog post by Jeremy Likness. For a working example, see the link below.
CommandingExample.zip (98.93 kb)

This work is licensed under a Creative Commons Attribution 3.0 Unported License.
Tags: .NET,
Silverlight,
MVVM
Categories: Design Patterns |
Microsoft .NET |
Silverlight