Created
August 3, 2017 10:27
-
-
Save spirit11/40f15043094b7bc5d96d398627b7ffed to your computer and use it in GitHub Desktop.
AsyncCommand
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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