Created
January 22, 2019 09:27
-
-
Save KirillAshikhmin/9ff9ee2161086d721462990477c68f3b to your computer and use it in GitHub Desktop.
Task RelayCommand for Xamarin.Forms
This file contains 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
using System; | |
using System.Threading.Tasks; | |
using System.Windows.Input; | |
using Xamarin.Forms; | |
using Xamarin.Forms.Internals; | |
namespace Project.Helpers | |
{ | |
public class RelayCommand : ICommand { | |
readonly Func<Task> _tsk; | |
readonly Func<object, Task> _tskParam; | |
bool _canExecute; | |
public RelayCommand(Func<object, Task> task, bool canExecute = true) { | |
_canExecute = canExecute; | |
_tskParam = task; | |
} | |
public RelayCommand(Func<Task> task, bool canExecute = true) { | |
_canExecute = canExecute; | |
_tsk = task; | |
} | |
public event EventHandler CanExecuteChanged; | |
public bool IsCanExecute { | |
get => _canExecute; | |
set { | |
_canExecute = value; | |
Device.BeginInvokeOnMainThread(() => { CanExecuteChanged?.Invoke(this, new EventArg<bool>(_canExecute)); }); | |
} | |
} | |
public bool CanExecute(object parameter) { | |
return _canExecute; | |
} | |
public async void Execute(object parameter) { | |
if (!_canExecute) return; | |
_canExecute = false; | |
CanExecuteChanged?.Invoke(this, new EventArg<bool>(_canExecute)); | |
if (_tskParam != null) await _tskParam?.Invoke(parameter); | |
if (_tsk != null) await _tsk?.Invoke(); | |
_canExecute = true; | |
CanExecuteChanged?.Invoke(this, new EventArg<bool>(_canExecute)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using