如何从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
,然后再设置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.
因此,在您的Application构造函数中,将其放置到NavigationPage
中,而不是仅创建LoginPage
,但隐藏导航栏,这样就不会影响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屋!