Xamarin Forms - How to create Commands with MVVM

Gordon S 501 Reputation points
2021-09-28T09:52:13.013+00:00

When creating a command (e.g. for a button), I would do so like this:

In the ViewModel class

public Command ConfirmLogoutCommand { get; }


    public LogoutPageViewModel()
    {
        ConfirmLogoutCommand = new Command(async () => await ExecuteConfirmLogoutCommand());
    }

    private async Task ExecuteConfirmLogoutCommand()
    {
        await Shell.Current.GoToAsync($"//{nameof(LoginPage)}");
    }

Which seems to work OK, but I get a warning on the "async" part that says "Avoid using 'async' lambda when delegate type returns 'void'"

How do I alter the basic code above to solve that issue?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,296 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,741 Reputation points Microsoft Vendor
    2021-09-29T02:39:02.017+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Please change the code like following format.

       public Command ConfirmLogoutCommand { get; }  
            public LogoutPageViewModel()  
            {  
                    ConfirmLogoutCommand = new Command( ExecuteConfirmLogoutCommand);  
            }  
         
                  
         
            private async void ExecuteConfirmLogoutCommand()  
               {  
                   await Shell.Current.GoToAsync($"//{nameof(LoginPage)}");  
               }  
    

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful