Guest User

Untitled

a guest
Jan 22nd, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. using System;
  2. using System.Threading.Tasks;
  3. using System.Windows.Input;
  4. using Xamarin.Forms;
  5. using Xamarin.Forms.Internals;
  6.  
  7. namespace Project.Helpers
  8. {
  9. public class RelayCommand : ICommand {
  10. readonly Func<Task> _tsk;
  11. readonly Func<object, Task> _tskParam;
  12. bool _canExecute;
  13.  
  14. public RelayCommand(Func<object, Task> task, bool canExecute = true) {
  15. _canExecute = canExecute;
  16. _tskParam = task;
  17. }
  18.  
  19. public RelayCommand(Func<Task> task, bool canExecute = true) {
  20. _canExecute = canExecute;
  21. _tsk = task;
  22. }
  23.  
  24. public event EventHandler CanExecuteChanged;
  25.  
  26. public bool IsCanExecute {
  27. get => _canExecute;
  28. set {
  29. _canExecute = value;
  30. Device.BeginInvokeOnMainThread(() => { CanExecuteChanged?.Invoke(this, new EventArg<bool>(_canExecute)); });
  31. }
  32. }
  33.  
  34. public bool CanExecute(object parameter) {
  35. return _canExecute;
  36. }
  37.  
  38. public async void Execute(object parameter) {
  39. if (!_canExecute) return;
  40. _canExecute = false;
  41. CanExecuteChanged?.Invoke(this, new EventArg<bool>(_canExecute));
  42. if (_tskParam != null) await _tskParam?.Invoke(parameter);
  43. if (_tsk != null) await _tsk?.Invoke();
  44. _canExecute = true;
  45. CanExecuteChanged?.Invoke(this, new EventArg<bool>(_canExecute));
  46. }
  47. }
  48. }
Add Comment
Please, Sign In to add comment