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 { /// /// 执行的方法 /// 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() is not false; } /// /// 执行方法 /// /// 参数 public async void Execute(object? parameter) { ExecuteAction?.Invoke(); await ExecuteAsync(); } /// /// 执行异步方法, 会在等待中关闭按钮的可执行性, 完成后恢复 /// /// 等待 private async Task ExecuteAsync() { if (ExecuteActionAsync is null) return; r_waiting.Value = true; await ExecuteActionAsync.Invoke(); r_waiting.Value = false; } /// /// 能否执行属性被改变事件 /// public event EventHandler? CanExecuteChanged; }