FieldWorkClient/Services/AsyncRelayCommand.cs

45 lines
1.2 KiB
C#
Raw Normal View History

2025-03-20 16:08:11 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Hopetry.Services
{
public class AsyncRelayCommand : ICommand
{
private readonly Func<Task> _executeAsync;
private readonly Func<bool> _canExecute;
public AsyncRelayCommand(Func<Task> executeAsync, Func<bool> canExecute = null)
{
_executeAsync = executeAsync ?? throw new ArgumentNullException(nameof(executeAsync));
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
// 这个方法决定了命令是否可执行
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
// 异步执行命令
public async void Execute(object parameter)
{
if (_executeAsync != null)
{
await _executeAsync(); // 执行异步操作
}
}
// 通知命令的可执行状态发生变化
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}