Skip to content

Instantly share code, notes, and snippets.

@jfromaniello
Created November 17, 2009 15:30
Show Gist options
  • Save jfromaniello/236998 to your computer and use it in GitHub Desktop.
Save jfromaniello/236998 to your computer and use it in GitHub Desktop.
public class RelayCommand : ICommand
{
#region Fields
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{ }
public RelayCommand(Action execute)
: this(o => execute())
{ }
public RelayCommand(Action execute, Func<bool> canExecute)
: this(o => execute(), o => canExecute())
{ }
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment