Skip to content

Instantly share code, notes, and snippets.

@spirit11
Created August 3, 2017 10:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spirit11/40f15043094b7bc5d96d398627b7ffed to your computer and use it in GitHub Desktop.
Save spirit11/40f15043094b7bc5d96d398627b7ffed to your computer and use it in GitHub Desktop.
AsyncCommand
class AsyncCommand : ICommand, INotifyPropertyChanged
{
public AsyncCommand(Func<Task> Action)
{
action = Action;
canExecute = true;
}
public event EventHandler CanExecuteChanged;
public event PropertyChangedEventHandler PropertyChanged;
public bool CanExecute(object parameter)
{
return !IsExecuting && canExecute;
}
public async void Execute(object parameter)
{
if (IsExecuting)
return;
try
{
IsExecuting = true;
await action();
}
catch
{
//
}
finally
{
IsExecuting = false;
}
}
public bool IsExecuting
{
get { return isExecuting; }
set
{
isExecuting = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsExecuting"));
OnCanExecuteChanged();
}
}
private bool isExecuting;
public void OverrideCanExecute(bool Value)
{
canExecute = Value;
OnCanExecuteChanged();
}
private Func<Task> action;
private bool canExecute;
private void OnCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment