How do you switch between two different Xamarin Fo

2019-05-02 03:23发布

问题:

I'm trying to figure out how to switch between two different pages in Xamarin Forms.

I do not wish to use a NavigationPage (which has that little back arrow that is auto displayed.

I have a Login page (which is a ContentPage) and once the person has authenticated, I then need to navigate to my Dashboard page (which is a TabbedPage).

eg.

Next, one of the Tab's in the TabbedPage is the profile of the logged in user. As such, I need to log them out. So i'll have a button to log them out, which means I will need to navigate them back to the Login page (which was that ContentPage).

I feel like I have two modes the user might be in.

  • UnAuthorized. (ContentPage)
  • Authorized. (TabbedPage).

It's like .. I need to change the App's MainPage to be either one of those two?

Can anyone help me, please?

回答1:

To change MainPage to another just do:

App.Current.MainPage = new NavigationPage(new MyContentPage());

or

App.Current.MainPage = new MyContentPage();

BTW: You can use a NavigationPage and then HIDE the toolbar with:

NavigationPage.SetHasNavigationBar(this, false);


回答2:

You can do navigation as usual by setting MainPage in your Application instance. Small sample.

namespace TestNavigation
{
    public class App : Application
    {
        public App ()
        {
            // The root page of your application
            MainPage = new MyPage1 ();
        }
    }
}


namespace TestNavigation
{
    public class MyPage1 : ContentPage
    {
        public MyPage1 ()
        {
            var button = new Button () {
                Text = "Click me"
            };
            button.Clicked += (object sender, EventArgs e) => {
                Application.Current.MainPage = new MyPage2 ();
            };
            Content = new StackLayout { 
                Children = {
                    button
                }
            };
        }
    }
}


namespace TestNavigation
{
    public class MyPage2 : ContentPage
    {
        public MyPage2 ()
        {
            Content = new StackLayout { 
                Children = {
                    new Label { Text = "Hello ContentPage" }
                }
            };
        }
    }
}

EDIT1

I submitted this answer but then I realised that I probably don't understand your problem.

EDIT2

Updated sample.



回答3:

If you like to switch between the pages then you can simply do

Application.Current.MainPage=new YourPage();

How to Change MainPage in xamarin forms at runtime?

this is what i have done to get result



回答4:

For a login page, the best practice is to use

await Navigation.PushModalAsync (new LoginPage());

Once you are on the LoginPage, you can use popModelAsync after the validation is passed:

await Navigation.PopModalAsync ();