Files
ShrlAlgoToolkit/Melskin/Utilities/RelayCommand.cs

51 lines
1.9 KiB
C#
Raw Normal View History

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