using System; using System.Threading.Tasks; using System.Windows.Input; namespace MauiAppStock.Helpers { public class AsyncCommand : ICommand { private readonly Func _execute; private readonly Func _canExecute; private bool _isExecuting; public AsyncCommand(Func execute, Func canExecute = null) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } public bool CanExecute(object parameter) { return !_isExecuting && (_canExecute?.Invoke() ?? true); } public async void Execute(object parameter) { if (!CanExecute(parameter)) return; try { _isExecuting = true; RaiseCanExecuteChanged(); await _execute(); } finally { _isExecuting = false; RaiseCanExecuteChanged(); } } public event EventHandler CanExecuteChanged; public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); } public class AsyncCommand : ICommand { private readonly Func _execute; private readonly Predicate _canExecute; private bool _isExecuting; public AsyncCommand(Func execute, Predicate canExecute = null) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } public bool CanExecute(object parameter) { return !_isExecuting && (_canExecute?.Invoke((T)parameter) ?? true); } public async void Execute(object parameter) { if (!CanExecute(parameter)) return; try { _isExecuting = true; RaiseCanExecuteChanged(); await _execute((T)parameter); } finally { _isExecuting = false; RaiseCanExecuteChanged(); } } public event EventHandler CanExecuteChanged; public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); } }