Skip to content

Instantly share code, notes, and snippets.

@AlbertoDePena
Created May 8, 2018 13:33
Show Gist options
  • Save AlbertoDePena/04c56eb0b9f73043a11782126d20316c to your computer and use it in GitHub Desktop.
Save AlbertoDePena/04c56eb0b9f73043a11782126d20316c to your computer and use it in GitHub Desktop.
public class DelegateCommand<T> : ICommand
{
private readonly Predicate<T> _canExecute;
private readonly Action<T> _execute;
public DelegateCommand(Action<T> execute) : this(execute, x => true)
{ }
public DelegateCommand(Action<T> execute, Predicate<T> canExecute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute ?? throw new ArgumentNullException(nameof(canExecute));
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => _canExecute((T)parameter);
public void Execute(object parameter) => _execute((T)parameter);
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
public class DelegateCommand : DelegateCommand<object>
{
public DelegateCommand(Action execute) : this(execute, () => true)
{ }
public DelegateCommand(Action execute, Func<bool> canExecute)
: base(x => execute(), x => canExecute()) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment