using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Input;
namespace HKW.HKWUtils.Observable;
///
/// 可观察命令
///
[DebuggerDisplay("\\{ObservableCommand, CanExecute = {IsCanExecute.Value}\\}")]
public class ObservableCommand : ObservableClass, ICommand
{
bool _isCanExecute = true;
///
/// 能执行的属性
///
public bool IsCanExecute
{
get => _isCanExecute;
set => SetProperty(ref _isCanExecute, value);
}
bool _currentCanExecute = true;
///
/// 当前可执行状态
///
/// 在执行异步事件时会强制为 , 但异步结束后会恢复为 的值
///
///
public bool CurrentCanExecute
{
get => _currentCanExecute;
private set => SetProperty(ref _currentCanExecute, value);
}
///
public ObservableCommand()
{
PropertyChanged += OnCanExecuteChanged;
}
private void OnCanExecuteChanged(object? sender, PropertyChangedEventArgs e)
{
CanExecuteChanged?.Invoke(this, new());
}
#region ICommand
///
/// 能否被执行
///
/// 参数
/// 能被执行为 否则为
public bool CanExecute(object? parameter)
{
return CurrentCanExecute && IsCanExecute;
}
///
/// 执行方法
///
/// 参数
public async void Execute(object? parameter)
{
if (IsCanExecute is not true)
return;
ExecuteCommand?.Invoke();
await ExecuteAsync();
}
///
/// 执行异步方法, 会在等待中修改 , 完成后恢复
///
/// 若要在执行此方法时触发 事件, 请将 设置为
///
///
/// 设置为 时触发 事件
/// 任务
public async Task ExecuteAsync(bool runAlone = false)
{
if (IsCanExecute is not true)
return;
if (runAlone)
ExecuteCommand?.Invoke();
if (ExecuteAsyncCommand is null)
return;
CurrentCanExecute = false;
foreach (
var asyncEvent in ExecuteAsyncCommand
.GetInvocationList()
.Cast()
)
await asyncEvent.Invoke();
CurrentCanExecute = true;
}
#endregion
#region Event
///
/// 能否执行属性改变后事件
///
public event EventHandler? CanExecuteChanged;
///
/// 执行事件
///
public event ExecuteEventHandler? ExecuteCommand;
///
/// 异步执行事件
///
public event ExecuteAsyncEventHandler? ExecuteAsyncCommand;
#endregion
}