我似乎在 .NET MAUI 或 .NET MAUI Community Toolkit 中找不到
AsyncCommand
。知道我可以找到什么包/命名空间吗?
.NET MAUI 工具包将不包含 Xamarin 的 MVVM 功能 社区工具包,例如 AsyncCommand。展望未来,我们将添加 将所有 MVVM 特定功能添加到新的 NuGet 包中, 社区工具包.MVVM.
即使问题已被标记为已解决,有人也可能会从 John Thiriet 编写的解决方案中受益。我实施了它并且效果很好。 https://johnthiriet.com/mvvm-going-async-with-async-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
}
然后就可以像在 Xamarin 中一样在 MAUI 中使用。
public MyMVVM()
{
MyCommand = new AsyncCommand(async()=> await MyMethod);
}
...
public AsynCommand MyCommand {get;}
安装CommunityToolkitMVVM 8.0.0
[RelayCommand]
async Task your_method (){...}
将 AsyncAwaitBestPractices.MVVM Nuget 包添加到您的项目中以恢复 AsyncCommand。
有关更多信息,请参阅 Github 项目页面:https://github.com/brminnick/AsyncAwaitBestPractices
public IAsyncRelayCommand ScanCommand => this.scanCommand ??= new AsyncRelayCommand(this.ScanNetworksAsync);