Thursday, December 1, 2011

A Simple Implementation of ICommand

MVVM pattern is kind of now an essential of building a WPF application, a very rich implementation is  of ICommand is DelegateCommand which came with Microsoft pattern and practice package enterprise library or prism framework also known as “Microsoft composite application block for WPF”. Bellow a simple implementation is given.

public class DelegateCommand : ICommand
{

public delegate void CommandOnExecute(object parameter);
public delegate bool CommandOnCanExecute(object parameter);

private readonly CommandOnExecute _execute;
private readonly CommandOnCanExecute _canExecute;

public DelegateCommand(CommandOnExecute onExecuteMethod,
CommandOnCanExecute onCanExecuteMethod)
{
_execute = onExecuteMethod;
_canExecute = onCanExecuteMethod;
}

#region ICommand Members

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}

public bool CanExecute(object parameter)
{
return _canExecute.Invoke(parameter);
}

public void Execute(object parameter)
{
_execute.Invoke(parameter);
}

#endregion
}

Bellow I have putdown the use of the DelegateCommand, note that this is not the class of prism, its hand written simple version, just named it DelegateCommand to make it looks like prism’s DelegateCommand.


public ICommand ApplyThemeCommand { get; set; }
public MainWindowPresenter()
{
Dictionary = new ResourceDictionary();
ApplyThemeCommand = new DelegateCommand(OnApplyThemeCommand, CanApplyThemeCommand);
}

private bool CanApplyThemeCommand(object parameter)
{
return true;
}

private void OnApplyThemeCommand(object parameter)
{
//code goes here
}

Xaml use is just like before simple binding with command object.


<Button Margin="5" Width="80" Height="25" 
Command="{Binding ApplyThemeCommand}"
CommandParameter="Blend">Blend</Button>
<Button Margin="5" Width="80" Height="25"
Command="{Binding ApplyThemeCommand}"
CommandParameter="Windows7">Windows 7</Button>

Hope this helps, until next time, Chow.

No comments:

Post a Comment