using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace HKW.HKWViewModels.SimpleObservable; /// /// 带参数的可观察命令 /// /// 参数类型 public class ObservableCommand : ICommand where T : notnull { /// public Action? ExecuteAction { get; set; } /// public Func? ExecuteActionAsync { get; set; } /// public Func? CanExecuteAction { get; set; } /// public ObservableValue CanExecuteProperty { get; } = new(true); /// private readonly ObservableValue r_waiting = new(false); /// public ObservableCommand() { CanExecuteProperty.PropertyChanged += InvokeCanExecuteChanged; r_waiting.PropertyChanged += InvokeCanExecuteChanged; } private void InvokeCanExecuteChanged( object? sender, System.ComponentModel.PropertyChangedEventArgs e ) { CanExecuteChanged?.Invoke(sender, e); } /// public bool CanExecute(object? parameter) { if (r_waiting.Value is true) return false; return CanExecuteAction is null ? CanExecuteProperty.Value : CanExecuteAction?.Invoke((T?)parameter) is not false; } /// public async void Execute(object? parameter) { ExecuteAction?.Invoke((T?)parameter); await ExecuteAsync((T?)parameter); } /// /// 参数 private async Task ExecuteAsync(T? parameter) { if (ExecuteActionAsync is null) return; r_waiting.Value = true; await ExecuteActionAsync.Invoke(parameter); r_waiting.Value = false; } /// public event EventHandler? CanExecuteChanged; }