83 lines
3.2 KiB
C#
83 lines
3.2 KiB
C#
|
|
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
|
|||
|
|
{
|
|||
|
|
add => CommandManager.RequerySuggested += value;
|
|||
|
|
remove => CommandManager.RequerySuggested -= value;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 判断命令是否可以执行。
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="parameter">传递给命令的参数。</param>
|
|||
|
|
/// <returns>返回一个布尔值,指示命令是否能够执行。对于此实现,总是返回true。</returns>
|
|||
|
|
public bool CanExecute(object? parameter)
|
|||
|
|
{
|
|||
|
|
if (canExecute == null) return true;
|
|||
|
|
|
|||
|
|
// 使用安全的类型获取机制,防止 InvalidCastException
|
|||
|
|
T? validParameter = GetSafeParameter(parameter);
|
|||
|
|
return canExecute(validParameter);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 执行命令。
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="parameter">传递给命令的参数。</param>
|
|||
|
|
public void Execute(object? parameter)
|
|||
|
|
{
|
|||
|
|
T? validParameter = GetSafeParameter(parameter);
|
|||
|
|
execute(validParameter);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 通知命令管理器重新查询此命令的CanExecute状态。
|
|||
|
|
/// 此方法用于在命令执行条件可能已更改时更新UI,手动更新,应对一些特殊场景,如倒计时功能结束,手动调用刷新按钮状态
|
|||
|
|
/// </summary>
|
|||
|
|
public void RaiseCanExecuteChanged() => CommandManager.InvalidateRequerySuggested();
|
|||
|
|
/// <summary>
|
|||
|
|
/// 安全地将 object 参数转换为泛型 T。如果类型不匹配,则返回 T 的默认值。
|
|||
|
|
/// </summary>
|
|||
|
|
private static T? GetSafeParameter(object? parameter)
|
|||
|
|
{
|
|||
|
|
if (parameter is T tParam)
|
|||
|
|
{
|
|||
|
|
return tParam;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 应对 WPF 绑定时可能会传入 null 的情况,特别是在 T 为值类型时
|
|||
|
|
return default;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
}
|