Files
ShrlAlgoToolkit/Melskin/Utilities/RelayCommand{T}.cs
2026-02-24 11:34:18 +08:00

79 lines
2.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Melskin.Utilities
{
/// <summary>
/// 一个简单的ICommand实现用于传递动作。此命令始终可以执行。
/// </summary>
internal class RelayCommand<T> : ICommand
{
private readonly Action<T?> execute;
private readonly Predicate<T?>? canExecute;
/// <summary>
/// 一个简单的ICommand实现用于传递动作。此命令始终可以执行。
/// </summary>
public RelayCommand(Action<T?> execute, Predicate<T?>? canExecute = null)
{
this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
this.canExecute = canExecute;
}
/// <summary>
/// 当命令的可执行状态更改时触发的事件。 广播此事件允许UI元素订阅并响应命令可执行性变化从而能够适时更新其状态如启用或禁用按钮
/// 通过将此事件与CommandManager.RequerySuggested关联可以确保每当应用程序中的命令状态可能改变时UI都会自动检查命令是否仍然可执行。
/// </summary>
public event EventHandler? CanExecuteChanged;
/// <summary>
/// 判断命令是否可以执行。
/// </summary>
/// <param name="parameter">传递给命令的参数。</param>
/// <returns>返回一个布尔值指示命令是否能够执行。对于此实现总是返回true。</returns>
public bool CanExecute(object? parameter)
{
if (canExecute == null) return true;
// 使用安全的类型获取机制,防止 InvalidCastException
return canExecute(GetSafeParameter(parameter));
}
/// <summary>
/// 执行命令。
/// </summary>
/// <param name="parameter">传递给命令的参数。</param>
public void Execute(object? parameter)
{
execute(GetSafeParameter(parameter));
}
/// <summary>
/// 通知命令管理器重新查询此命令的CanExecute状态。
/// 此方法用于在命令执行条件可能已更改时更新UI
/// </summary>
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// 安全地将 object 参数转换为泛型 T。如果类型不匹配则返回 T 的默认值。
/// </summary>
private static T? GetSafeParameter(object? parameter)
{
if (parameter is T tParam)
{
return tParam;
}
// 应对 WPF 绑定时可能会传入 null 的情况,特别是在 T 为值类型时
return default;
}
}
}