Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - How to remove a modal page from NavigationStack in Xamarin.Forms

Here's an example for my Navigation:

LoginPage ( Login_Click  ) -> MainPage   | Block BackButton
MainPage  ( Logout_Click ) -> LoginPage  | Block going back to the MainPage

Currently I am using this code to show the MainPage after a successful login.

 await Navigation.PushModalAsync(new MainPage());

I DON'T want the users to go back by hitting the PreviousButton(Android) to return to the LoginPage.

Same story when logging out.

Is there a way to remove the LoginPage from the NavigationStack after a successful login (and remove the MainPage when logged out) ?

NOTE:

This is modal. I am not using a NavigationPage.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are looking for PopToRootAsync. So your user enters required info and they tap a login button, you perform your login verification and if success you set a new MainPage and then PopToRootAsync which pops all but the root Page off the navigation stack.

Update: Due to the way PopToRootAsync is done across the various platforms, you need to start from a NavigationPage but can remove it as your root page after your login process.

So in your Application constructor, instead of just creating your LoginPage, place it into a NavigationPage but hide the navigation bar so it does not effect your LoginPage screen layout:

public App()
{
    var navPage = new NavigationPage(new LoginPage());
    NavigationPage.SetHasNavigationBar(navPage.CurrentPage, false);
    MainPage = navPage;
}

Then within your LoginPage you can set the Application.Current.MainPage to any Page class (does not have to be a NavigationPage) and then PopToRootAsync to get to it and totally remove your LoginPage from the navigation hierarchy.

public partial class LoginPage : ContentPage
{
    public LoginPage()
    {
        InitializeComponent();
        loginDone.Clicked += OnLoginClick;
    }
    async void OnLoginClick(object sender, EventArgs e)
    {
        // If Login is complete/successful - set new root page
        if (YourLoginMethod()) {
            Application.Current.MainPage = new MainApplicationPage();
            // Pops all but the root Page off the navigation stack, with optional animation.
            await Navigation.PopToRootAsync(true);
        }
    }
}

Note: Tested this technique only on iOS and Android


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...