question

NicholasR-0309 avatar image
0 Votes"
NicholasR-0309 asked ·

Xamarin Forms: How do you Navigate to a New View Immediately After the Previous View Loads Using ViewModels

In my app, users have to login the first time, but a token is generated to allow them to skip the login process on subsequent logins. The login page checks that the token is correct in its viewmodel constructor, calling Shell.Current.GoToAsync() if it is. This does not work as it should, as the login page was not completely loaded when the new page was pushed, and will load on top of the new page. I have tried the workaround in this question, but that does not work either. Here's a part of the code:

         public LoginPageViewModel()
         {
             userData = (Application.Current as App).userData;
             SendLogin = new Command(Login);
             TokenLogin();
         }
    
         //Attempts to login via token
         private async void TokenLogin()
         {
             string user = Tokenizer.GetTokenUser();
             string token = Tokenizer.GetToken();
             if(userData.TokenLogin(user, token))
             {
                 await Shell.Current.GoToAsync(nameof(CategoryPage));//Login successful
             }
         }



dotnet-xamarinforms
10 |1000 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.

sphauck avatar image
0 Votes"
sphauck answered ·

Look for the token on startup and then don't even go to the login window, go directly to the "second form"
FYI, if you are storing a "token" make sure you are using secure storage
https://docs.microsoft.com/en-us/xamarin/essentials/secure-storage?context=xamarin%2Fandroid&tabs=ios

·
10 |1000 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.

ColeXia-MSFT avatar image
0 Votes"
ColeXia-MSFT answered ·

Hello,

Welcome to Microsoft Q&A!

The better way is that set LoginPage as MainPage at first ,and then change App.Current.MainPage upon login successfully .

App


MainPage =  new LoginPage();


LoginPageViewModel


private async void TokenLogin()
         {
             string user = Tokenizer.GetTokenUser();
             string token = Tokenizer.GetToken();
             if(userData.TokenLogin(user, token))
             {
                 App.Current.MainPage = new AppShell();
             }
         }


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.

·
10 |1000 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.