using System.Windows.Input;
namespace Titano.Ui.Mvvm;
/// Synchronous command with optional can-execute predicate.
public sealed class RelayCommand(Action execute, Func? canExecute = null) : ICommand
{
public RelayCommand(Action execute, Func? canExecute = null)
: this(_ => execute(), canExecute is null ? null : _ => canExecute())
{
}
public event EventHandler? CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object? parameter) => canExecute?.Invoke(parameter) ?? true;
public void Execute(object? parameter) => execute(parameter);
}
/// Asynchronous command that disables itself while running and reports failures through .
public sealed class AsyncRelayCommand(Func execute, Func? canExecute = null) : ICommand
{
private CancellationTokenSource? _cts;
public AsyncRelayCommand(Func execute, Func? canExecute = null)
: this((_, _) => execute(), canExecute is null ? null : _ => canExecute())
{
}
public event EventHandler? CanExecuteChanged;
/// Raised on the UI thread when the command throws (other than cancellation).
public static event Action? Failed;
public bool IsRunning => _cts is not null;
public bool CanExecute(object? parameter) => !IsRunning && (canExecute?.Invoke(parameter) ?? true);
public async void Execute(object? parameter)
{
if (!CanExecute(parameter)) return;
_cts = new CancellationTokenSource();
RaiseCanExecuteChanged();
try
{
await execute(parameter, _cts.Token);
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
Failed?.Invoke(ex);
}
finally
{
_cts.Dispose();
_cts = null;
RaiseCanExecuteChanged();
}
}
public void Cancel() => _cts?.Cancel();
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}