Implémentation d’une ICommand de façon gÃ...23 août 2011

Boîte à outils

Dans un précédent article (Le design pattern MVVM), je vous présentais ce qui devenait un standard grandissant dans le monde du développment Microsoft WPF.

Dans cet article, je vous proposais déjà une implémentation de ICommand permettant d’attacher à un évènement simple de la vue, un bout de code de votre choix.

Voici une amélioration de cette classe GenericCommand dans une version templatée (générique) qui vous apportera plus de flexibilité.

GenericCommand<T>

public class GenericCommand<T> : ICommand
{
    public GenericCommand()
    {
            
    }

    public GenericCommand(Action<T> executeDelegate, Predicate<T> canExecuteDelegate = null)
    {
        CanExecuteDelegate = canExecuteDelegate;
        ExecuteDelegate = executeDelegate;
    }

    public Predicate<T> CanExecuteDelegate { get; set; }
    public Action<T> ExecuteDelegate { get; set; }

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

    public bool CanExecute(object parameter)
    {
        return CanExecuteDelegate == null || CanExecuteDelegate((T)parameter);
    }

    public void RaiseCanExecuteChanged()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, EventArgs.Empty);
    }

    public event EventHandler CanExecuteChanged;
}

SimpleCommand

public class SimpleCommand : GenericCommand<object>
{
    public SimpleCommand(Action executeDelegate, Func<bool> canExecuteDelegate = null)
        : base(o => executeDelegate(), canExecuteDelegate == null ? (Predicate<object>)null : o => canExecuteDelegate())
    {
    }
}