Skip to content

Instantly share code, notes, and snippets.

@mscottreed
Created June 24, 2015 11:20
Show Gist options
  • Save mscottreed/a80b4d24a581c12d8d89 to your computer and use it in GitHub Desktop.
Save mscottreed/a80b4d24a581c12d8d89 to your computer and use it in GitHub Desktop.
DelegateCommand
public class DelegateCommand<T> : ICommand
{
readonly Func<T, bool> canExecute = _ => true;
readonly Action<T> executeAction;
bool canExecuteCache;
public DelegateCommand(Action<T> executeAction, Func<T, bool> canExecute)
{
this.executeAction = executeAction;
this.canExecute = canExecute;
}
public DelegateCommand(Action<T> executeAction)
{
this.executeAction = executeAction;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (canExecute != null)
{
bool temp = canExecute((T)parameter);
if (canExecuteCache != temp)
{
canExecuteCache = temp;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, new EventArgs());
}
}
return canExecuteCache;
}
return true;
}
public void Execute(object parameter)
{
executeAction((T)parameter);
}
public event EventHandler CanExecuteChanged;
#endregion
}
//Non generic
public class DelegateCommand : DelegateCommand<object>
{
public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
: base(executeAction, canExecute)
{
}
public DelegateCommand(Action<object> executeAction)
: base(executeAction)
{
}
}
public class AsyncDelegateCommand : DelegateCommand<object>
{
public AsyncDelegateCommand(Func<object, Task> executeAction, Func<object, bool> canExecute)
: base(async o => await executeAction(o), canExecute)
{
}
public AsyncDelegateCommand(Func<object, Task> executeAction)
: base(async o => await executeAction(o))
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment