How to Change MainPage in xamarin forms at runtime?

10,874

You need to look at doing navigation, not changing the routes for these paths. Take a look at the Xamarin Navigation docs here: https://developer.xamarin.com/guides/cross-platform/xamarin-forms/getting-started/introduction-to-xamarin-forms/#Navigation

await Navigation.PushModalAsync(new LoginPage());
Share:
10,874
Narendra
Author by

Narendra

Updated on June 20, 2022

Comments

  • Narendra
    Narendra about 2 years

    In xamarin forms,RootPage with master detail Layout. My task is to show that page after user successful login. I am using azure mobile service for login. I spend more time to get result.I saw some other solutions but those solution does not render master detail as expected.Finally i got the solution.

    Here is the code in app.cs

    public App()
        {
    
         Client = new MobileServiceClient("your azure url", "your master key");
            LoadMainPage();
    
        } public void LoadMainPage()
        {
            if (Client.CurrentUser == null)
            {
                MainPage=new NavigationPage(new SplashPage());
            }
            else
            {
                MainPage = new RootView();;
            }
    
    
        }
    

    In Login page

     async void  OnLoginClicked(object sender, EventArgs args)
        {
            MobileServiceUser user;
    
            try
            {
                user = await DependencyService.Get<IMobileClient>().LoginAsync(MobileServiceAuthenticationProvider.Facebook);
                Application.Current.MainPage=new RootView();
                await Navigation.PopToRootAsync();
    
            }
            catch (InvalidOperationException ex)
            {
                if (ex.Message.Contains("Authentication was cancelled"))
                {
                    //messageLabel.Text = "Authentication cancelled by the user";
                }
            }
            catch (Exception ex)
            {
              //  messageLabel.Text = "Authentication failed";
            }
    
        }
    
  • Efe
    Efe over 6 years
    Thanks. Nice point! This way, I can navigate to my Login page whenever I get a webapi AccessToken Expired.