using System.Windows.Input; namespace Melskin.Utilities; /// /// 一个简单的ICommand实现,用于传递动作。 /// internal class RelayCommand : ICommand { private readonly Action execute; private readonly Predicate? canExecute; /// /// 当命令的可执行状态更改时发生的事件。 广播此事件通知UI,当命令的CanExecute方法返回值发生变化时,需要重新查询命令的状态。 /// public event EventHandler? CanExecuteChanged; /// /// 初始化 RelayCommand 的新实例。 /// /// 命令执行的逻辑。 /// 判断命令是否可以执行的逻辑(可选)。如果为 null,则命令始终可执行。 /// execute 为 null 时抛出。 public RelayCommand(Action execute, Predicate? canExecute = null) { this.execute = execute ?? throw new ArgumentNullException(nameof(execute)); this.canExecute = canExecute; } /// /// 判断命令是否可以执行。 /// /// 传递给命令的参数。 /// 返回一个布尔值,指示命令是否能够执行。对于此实现,总是返回true。 public bool CanExecute(object? parameter) => canExecute == null || canExecute(parameter); /// /// 执行命令。 /// /// 传递给命令的参数。 public void Execute(object? parameter) => execute(parameter); /// /// 手动通知 UI 刷新此按钮的状态。 /// public void RaiseCanExecuteChanged() { // 触发事件,通知订阅了此命令的 UI 控件 CanExecuteChanged?.Invoke(this, EventArgs.Empty); } }