Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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));
- }
- }
- }
Add Comment
Please, Sign In to add comment