我在ac#wpf mvvm应用程序中有一个asyncRelayCommand无法正常工作,我有点理解我需要一种方法,但是我所经历的指南并未提及如何制作一个https://johnthiriet.com/mvvm-going-async-with-async-command/的指南经历了,这是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight;
namespace DataConverter.Command
{
public interface IAsyncCommand<T> : ICommand
{
Task ExecuteAsync(T parameter);
bool CanExecute(T parameter);
}
public class AsyncCommand<T> : IAsyncCommand<T>
{
public event EventHandler CanExecuteChanged;
private bool _isExecuting;
private readonly Func<T,Task> _execute;
private readonly Func<T,bool> _canExecute;
private readonly IErrorHandler _errorHandler;
public AsyncCommand(Func<T,Task> execute,Func<T,bool> canExecute = null,IErrorHandler errorHandler = null)
{
_execute = execute;
_canExecute = canExecute;
_errorHandler = errorHandler;
}
public bool CanExecute(T parameter)
{
return !_isExecuting && (_canExecute?.Invoke(parameter) ?? true);
}
public async Task ExecuteAsync(T parameter)
{
if (CanExecute(parameter))
{
try
{
_isExecuting = true;
await _execute(parameter);
}
finally
{
_isExecuting = false;
}
}
RaiseCanExecuteChanged();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this,EventArgs.Empty);
}
#region Explicit implementations
bool ICommand.CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
void ICommand.Execute(object parameter)
{
ExecuteAsync((T)parameter).FireAndForgetSafeAsync(_errorHandler);
}
#endregion
}
}
任何人都可以告诉我如何制作一个,这样才能奏效。我真的不明白为什么指南没有提到它,但是是