如何从 Xamarin.Forms 中的 NavigationStack 中删除模态页面 [英] How to remove a modal page from NavigationStack in Xamarin.Forms
问题描述
这是我的Navigation
的示例:
Here's an example for my Navigation
:
LoginPage ( Login_Click ) -> MainPage | Block BackButton
MainPage ( Logout_Click ) -> LoginPage | Block going back to the MainPage
目前我正在使用此代码在成功登录后显示MainPage
.
Currently I am using this code to show the MainPage
after a successful login.
await Navigation.PushModalAsync(new MainPage());
我不希望用户通过点击PreviousButton(Android)
返回登录页面.
I DON'T want the users to go back by hitting the PreviousButton(Android)
to return to the LoginPage.
注销时相同的故事.
有没有办法在成功登录后从 NavigationStack 中删除 LoginPage(并在注销时删除 MainPage)?
Is there a way to remove the LoginPage from the NavigationStack after a successful login (and remove the MainPage when logged out) ?
注意:
这是模态的.我没有使用 NavigationPage.
This is modal. I am not using a NavigationPage.
推荐答案
您正在寻找 PopToRootAsync
.因此,您的用户输入所需的信息并点击登录按钮,您执行登录验证,如果成功,您设置一个新的 MainPage
,然后设置一个新的 MainPage
然后 PopToRootAsync
弹出除根页面之外的所有页面离开导航堆栈.
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.
更新:由于 PopToRootAsync
在各种平台上完成的方式,您需要从 NavigationPage
开始,但可以将其删除为登录过程后的根页面.
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.
因此,在您的应用程序构造函数中,不要只创建您的 LoginPage
,而是将其放入 NavigationPage
但隐藏导航栏不会影响您的 LoginPage
屏幕布局:
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;
}
然后在您的 LoginPage
中,您可以将 Application.Current.MainPage
设置为任何 Page
类(不> 必须是一个 NavigationPage
) 然后 PopToRootAsync
才能到达它并从导航层次结构中完全删除您的 LoginPage
.
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);
}
}
}
注意:仅在 iOS
和 Android
这篇关于如何从 Xamarin.Forms 中的 NavigationStack 中删除模态页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!