question

GordonS-9701 avatar image
0 Votes"
GordonS-9701 asked LeonLu-MSFT answered

Xamarin Forms - How to create Commands with MVVM

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?



dotnet-xamarinforms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered

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.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.