I can't seem to find AsyncCommand
in .NET MAUI or .NET MAUI Community Toolkit. Any idea what package/namespace I can find it?
install CommunityToolkitMVVM 8.0.0
[RelayCommand]
async Task your_method (){...}
The .NET MAUI Toolkit will not contain the MVVM features from Xamarin Community Toolkit, like AsyncCommand. Going forward, we will be adding all MVVM-specifc features to a new NuGet Package, CommunityToolkit.MVVM.
AsyncCommand
in favor of AsyncRelayCommand
–
Drinker WeakEventManager
or is it not necessary using the AsyncCommand
? –
Strathspey Even if the question has been marked as solved, someone might profit from this solution written by John Thiriet. I implemented it and it worked fine. 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
}
Then it can be used in MAUI just like in Xamarin.
public MyMVVM()
{
MyCommand = new AsyncCommand(async()=> await MyMethod);
}
...
public AsynCommand MyCommand {get;}
install CommunityToolkitMVVM 8.0.0
[RelayCommand]
async Task your_method (){...}
Add the AsyncAwaitBestPractices.MVVM Nuget package to your project to get the AsyncCommand back.
For more information see the Github project page: https://github.com/brminnick/AsyncAwaitBestPractices
- Install nuget package CommunityToolkit.Mvvm.
- Declare IAsyncRelayCommand and create an instance of AsyncRelayCommand, just like that:
public IAsyncRelayCommand ScanCommand => this.scanCommand ??= new AsyncRelayCommand(this.ScanNetworksAsync);
© 2022 - 2024 — McMap. All rights reserved.