61 Zeilen
1.5 KiB
C#
61 Zeilen
1.5 KiB
C#
using System.Windows.Input;
|
|
|
|
namespace PrinterMonitor.ViewModels;
|
|
|
|
public class RelayCommand : ICommand
|
|
{
|
|
private readonly Action _execute;
|
|
private readonly Func<bool>? _canExecute;
|
|
|
|
public RelayCommand(Action execute, Func<bool>? canExecute = null)
|
|
{
|
|
_execute = execute;
|
|
_canExecute = canExecute;
|
|
}
|
|
|
|
public event EventHandler? CanExecuteChanged
|
|
{
|
|
add => CommandManager.RequerySuggested += value;
|
|
remove => CommandManager.RequerySuggested -= value;
|
|
}
|
|
|
|
public bool CanExecute(object? parameter) => _canExecute?.Invoke() ?? true;
|
|
public void Execute(object? parameter) => _execute();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Führt ein async-Lambda als ICommand aus.
|
|
/// Während der Ausführung ist CanExecute=false (verhindert Doppelklick).
|
|
/// </summary>
|
|
public class AsyncRelayCommand : ICommand
|
|
{
|
|
private readonly Func<Task> _execute;
|
|
private bool _isExecuting;
|
|
|
|
public AsyncRelayCommand(Func<Task> execute)
|
|
{
|
|
_execute = execute;
|
|
}
|
|
|
|
public event EventHandler? CanExecuteChanged
|
|
{
|
|
add => CommandManager.RequerySuggested += value;
|
|
remove => CommandManager.RequerySuggested -= value;
|
|
}
|
|
|
|
public bool CanExecute(object? parameter) => !_isExecuting;
|
|
|
|
public async void Execute(object? parameter)
|
|
{
|
|
_isExecuting = true;
|
|
CommandManager.InvalidateRequerySuggested();
|
|
try { await _execute(); }
|
|
finally
|
|
{
|
|
_isExecuting = false;
|
|
CommandManager.InvalidateRequerySuggested();
|
|
}
|
|
}
|
|
}
|
|
|