using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Melskin.Utilities
{
///
/// 一个简单的ICommand实现,用于传递动作。此命令始终可以执行。
///
internal class RelayCommand : ICommand
{
private readonly Action execute;
private readonly Predicate? canExecute;
///
/// 一个简单的ICommand实现,用于传递动作。此命令始终可以执行。
///
public RelayCommand(Action execute, Predicate? canExecute = null)
{
this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
this.canExecute = canExecute;
}
///
/// 当命令的可执行状态更改时触发的事件。
/// 广播此事件允许UI元素订阅并响应命令可执行性变化,从而能够适时更新其状态(如启用或禁用按钮)。
/// 通过将此事件与CommandManager.RequerySuggested关联,可以确保每当应用程序中的命令状态可能改变时,UI都会自动检查命令是否仍然可执行。
///
public event EventHandler? CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
///
/// 判断命令是否可以执行。
///
/// 传递给命令的参数。
/// 返回一个布尔值,指示命令是否能够执行。对于此实现,总是返回true。
public bool CanExecute(object? parameter)
{
if (canExecute == null) return true;
// 使用安全的类型获取机制,防止 InvalidCastException
T? validParameter = GetSafeParameter(parameter);
return canExecute(validParameter);
}
///
/// 执行命令。
///
/// 传递给命令的参数。
public void Execute(object? parameter)
{
T? validParameter = GetSafeParameter(parameter);
execute(validParameter);
}
///
/// 通知命令管理器重新查询此命令的CanExecute状态。
/// 此方法用于在命令执行条件可能已更改时更新UI,手动更新,应对一些特殊场景,如倒计时功能结束,手动调用刷新按钮状态
///
public void RaiseCanExecuteChanged() => CommandManager.InvalidateRequerySuggested();
///
/// 安全地将 object 参数转换为泛型 T。如果类型不匹配,则返回 T 的默认值。
///
private static T? GetSafeParameter(object? parameter)
{
if (parameter is T tParam)
{
return tParam;
}
// 应对 WPF 绑定时可能会传入 null 的情况,特别是在 T 为值类型时
return default;
}
}
}