Skip to content

Instantly share code, notes, and snippets.

@AlekseyGett
Created December 8, 2017 09:18
Show Gist options
  • Save AlekseyGett/9007f27231681ba4340ce1741b6d2fc6 to your computer and use it in GitHub Desktop.
Save AlekseyGett/9007f27231681ba4340ce1741b6d2fc6 to your computer and use it in GitHub Desktop.
Implementation of ICommand interface
using System;
using System.Windows.Input;
namespace MVVM
{
public class ActionCommand : ICommand
{
private Action<object> action;
private Predicate<object> predicate;
public ActionCommand(Action<object> action) : this(action, null)
{ }
public ActionCommand(Action<object> action, Predicate<object> predicate)
{
this.action = action ?? throw new ArgumentNullException(nameof(action));
this.predicate = predicate;
}
#region ICommand members:
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter) =>
predicate == null || predicate(parameter);
public void Execute() =>
Execute(null);
public void Execute(object parameter) =>
action(parameter);
#endregion
}
}
using System;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVM
{
public class ActionCommandAsync : ICommand
{
private Func<object, Task> action;
private Predicate<object> predicate;
private bool executing = false;
public ActionCommandAsync(Func<object, Task> action) : this(action, null)
{ }
public ActionCommandAsync(Func<object, Task> action, Predicate<object> predicate)
{
this.action = action ?? throw new ArgumentNullException(nameof(action));
this.predicate = predicate;
}
#region ICommand members:
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter) =>
!executing && (predicate == null || predicate(parameter));
public void Execute() =>
Execute(null);
public async void Execute(object parameter)
{
var task = action(parameter);
if (task != null)
{
executing = true;
await task;
executing = false;
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment