【发布时间】:2023-01-31 06:23:31
【问题描述】:
我似乎无法在 .NET MAUI 或 .NET MAUI Community Toolkit 中找到 AsyncCommand。知道我能找到什么包/命名空间吗?
【问题讨论】:
标签: xamarin xamarin.forms .net-maui xamarin-community-toolkit maui-community-toolkit
我似乎无法在 .NET MAUI 或 .NET MAUI Community Toolkit 中找到 AsyncCommand。知道我能找到什么包/命名空间吗?
【问题讨论】:
标签: xamarin xamarin.forms .net-maui xamarin-community-toolkit maui-community-toolkit
.NET MAUI 工具包将不包含 Xamarin 的 MVVM 功能 社区工具包,例如 AsyncCommand。展望未来,我们将添加 所有 MVVM 特定的功能到一个新的 NuGet 包, CommunityToolkit.MVVM。
【讨论】:
AsyncCommand,转而支持AsyncRelayCommand
即使它已被标记为已解决,有人可能会从这个解决方案中获益,该解决方案确实写得非常好 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
}
【讨论】:
安装 CommunityToolkitMVVM 8.0.0
[RelayCommand]
async Task your_method (){...}
【讨论】: