# Monday, 24 May 2010

Silverlight 4 and ICommand

Silverlight 4 offers the opportunity to databind against a command. This is useful in MVVM scenarios. For some reason there is no quick implementation of a command (or I have been unable to locate it) so I wrote my own ‘QuickCommand’:

#region QuickCommand
public delegate void Execute( object parameter );
public delegate bool CanExecute( object parameter );

public class QuickCommand : ICommand
{

    private Execute _executeMethod;
    private CanExecute _canExecuteMethod;

    public QuickCommand()
        : this( null, null )
    {
    }

    public QuickCommand( Execute executeMethod )
        : this( executeMethod, null )
    {
    }

    public QuickCommand( Execute executeMethod, CanExecute canExecuteMethod )
    {
        _executeMethod = executeMethod;
        _canExecuteMethod = canExecuteMethod;
    }


    #region ICommand Members

    public bool CanExecute( object parameter )
    {
        if ( _canExecuteMethod == null )
        {
            return true;
        }
        else
        {
            return _canExecuteMethod( parameter );
        }
    }

    public event EventHandler CanExecuteChanged;

    public void Execute( object parameter )
    {
        if ( _executeMethod != null )
        {
            _executeMethod( parameter );
        }
    }

    #endregion
}
#endregion QuickCommand

The Quick command allows you to assign a lambda expression to a ICommand property like this:

public class MainView
{
    public MainView()
    {
        About = new QuickCommand( c => MessageBox.Show( "© Develop-one, 2010" ) );
    }

    public ICommand About { get; set; }
}

This ICommand property can then be used for databinding a button control (I removed the default namespace declarations):

<UserControl ... 
    xmlns:ViewModel="clr-namespace:DevelopOne.Sample.ViewModel">
    <UserControl.DataContext>
        <ViewModel:MainView/>
    </UserControl.DataContext>
<StackPanel Orientation="Vertical">
    <HyperlinkButton Content="About" Name="hyperlinkButton1" HorizontalAlignment="Center" Command="{Binding About}"/>
</StackPanel>
</UserControl>

See how the ‘Command’-property of the button binds against ‘About’-property of the MainView class? Sweet!

#    Comments [0] |