ViewModel with async Command

0
0

Hi guys,

If I have a ViewModel with an async method, how can I define a Command to bind to a button in my View?
The problem I see is that when I click the Login button, I am not navigated from my login View to my main view, but if I click somewhere on the page, then the navigation happens indeed. If I remove async from the method, this works from the first click.
I am reading in the docs about Application.Update(this), but I don’t think it is reasonable to call Application.Update(this) from the ViewModel, what “this” should be in that case?

Is this even possible, or am I trying in vain?

Best regards,
Alex

For example, I have a LoginViewModel with the following method.

private async Task LoginAsync()
    {
        try
        {
            IsBusy = true;
            ErrorMessage = string.Empty;
            var success = await _authService.LoginAsync(Username, Password);
            if (!success)
                ErrorMessage = “Invalid username or password.”;
            // If success, AuthenticationService will raise event and ApplicationViewModel will handle shell swap
        }
        catch (Exception ex)
        {
            ErrorMessage = $”Login failed: {ex.Message}”;
        }
        finally
        {
            IsBusy = false;
        }
    }

And I am trying to define my command in the constructor:

public LoginViewModel(IAuthenticationService authService)
    {
        _authService = authService;
        LoginCommand = new Command(
            execute: async () => { await LoginAsync(); },
            canExecute: () => !IsBusy && !string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password));
    }

and in my LoginView:

btnLogin.Command = _vm.LoginCommand;

 

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.