Home > Back-end >  How can I pass CommandParameter into AsyncCommand?
How can I pass CommandParameter into AsyncCommand?

Time:12-31

I want to run the button command asynchronously. The following application can run asynchronously. But I couldn't find how to pass the CommandParamater that I specified on the xaml side into the event.

What kind of application should I make? I would be glad if you help.

AsyncCommand.cs & IAsyncCommand

    public interface IAsyncCommand : ICommand
{
    Task ExecuteAsync(object parameter);
}

public class AsyncCommand : AsyncCommandBase
{
    private readonly Func<Task> _command;
    public AsyncCommand(Func<Task> command)
    {
        _command = command;
    }
    public override bool CanExecute(object parameter)
    {
        return true;
    }
    public override Task ExecuteAsync(object parameter)
    {
        return _command();
    }

}

AsyncCommandBase.cs

    public abstract class AsyncCommandBase : IAsyncCommand
{
    public abstract bool CanExecute(object parameter);
    public abstract Task ExecuteAsync(object parameter);
    public async void Execute(object parameter)
    {
        await ExecuteAsync(parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested  = value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    protected void RaiseCanExecuteChanged()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

ViewModel

   ChangePageCommand = new AsyncCommand(async () => await ChangePageClick());

CodePudding user response:

You would change the type of your delegate from Func<Task> (a method taking no parameters and returning Task) to Func<object, Task> (a method taking a single object parameter and returning Task):

private readonly Func<object, Task> _command;
public AsyncCommand(Func<object, Task> command) => _command = command;
public override Task ExecuteAsync(object parameter) => _command(parameter);
  • Related