[MVVM] RelayCommand

A continuación comparto una implementación del RelayCommand que estoy usando para trabajar con MVVM y PCL (Portable Class Library).

IRelayCommand.cs


public interface IRelayCommand : ICommand
{
void RaiseCanExecuteChanged();
}

RelayCommand class


public class RelayCommand : IRelayCommand
{
#region Fields

private readonly Action _execute;
private readonly Func<bool> _canExecute;

#endregion Fields

#region Constructors

public RelayCommand(Action execute)
: this(execute, null)
{
}

public RelayCommand(Action execute, Func<bool> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}

#endregion Constructors

#region ICommand Members

public bool CanExecute(object parameter)
{
return null == _canExecute ? true : _canExecute();
}

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

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

public event EventHandler CanExecuteChanged;

#endregion ICommand Members
}

RelayCommand<T> class


public class RelayCommand<T> : IRelayCommand
{
#region Fields

private readonly Action<T> _execute;
private readonly Func<T, bool> _canExecute;

#endregion Fields

#region Constructors

public RelayCommand(Action<T> execute)
: this(execute, null)
{
}

public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}

#endregion Constructors

#region ICommand Members

public bool CanExecute(object parameter)
{
parameter = null == parameter ? default(T) : parameter;
return null == _canExecute ? true : _canExecute((T)parameter);
}

public void Execute(object parameter)
{
parameter = null == parameter ? default(T) : parameter;
_execute((T)parameter);
}

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

public event EventHandler CanExecuteChanged;

#endregion ICommand Members
}

¿Como usar?


#region Command Members

private RelayCommand aceptarCommand;

#endregion Command Members

#region Command Properties

public RelayCommand AceptarCommand
{
get
{
if (null == aceptarCommand)
aceptarCommand = new RelayCommand(AceptarExecute, AceptarCanExecute);

return aceptarCommand;
}
}

#endregion Command Properties

#region Command Methods

private bool AceptarCanExecute()
{
return true;
}

private void AceptarExecute()
{
}

#endregion Command Methods

Agregue un comentario

Su dirección de correo no se hará público.