Skip to content

Instantly share code, notes, and snippets.

@KirillAshikhmin
Created January 22, 2019 09:27
Show Gist options
  • Save KirillAshikhmin/9ff9ee2161086d721462990477c68f3b to your computer and use it in GitHub Desktop.
Save KirillAshikhmin/9ff9ee2161086d721462990477c68f3b to your computer and use it in GitHub Desktop.
Task RelayCommand for Xamarin.Forms
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));
}
}
}
@KirillAshikhmin
Copy link
Author

Using


		RelayCommand MyCommand { get; }
		public ProductReplacementViewCell() {
			MyCommand = new RelayCommand(MyCommandExecute);
		}

		Task MyCommandExecute(object arg) {
			//await method execute
		}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment