在我的应用程序中,我正在使用 a 推送页面,NavigationPage
并且在某个阶段我想回到堆栈中的前一页面。这是我的结构:
NavigationPage > Page1 > Page2 > Page3 > Page4
如何PopAsync
不经过Page3直接从Page4返回Page2?
在我的应用程序中,我正在使用 a 推送页面,NavigationPage
并且在某个阶段我想回到堆栈中的前一页面。这是我的结构:
NavigationPage > Page1 > Page2 > Page3 > Page4
如何PopAsync
不经过Page3直接从Page4返回Page2?
如果您有一个想要弹出的计数,这非常有效。
for (var counter = 1; counter < BackCount; counter++)
{
Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]);
}
await Navigation.PopAsync();
我试图做同样的事情 - 我最终做的有点像黑客,但确实有效并且保持第 2 页的后退按钮转到第 1 页。
基本上,
var page3 = _navi.NavigationStack.FirstOrDefault(p => p is Page3Type);
if(page3 != null)
{
_navi.RemovePage(page3);
}
await navi.PopAsync();
这首先(如果存在)删除 page3。现在它已经消失了,它会弹出,然后你又回到了第 2 页。
我提供了一个解决方案,只要您有参考,它就可以返回到特定页面:
protected async Task PopToPage(Page destination)
{
if (destination == null) return;
//First, we get the navigation stack as a list
var pages = Navigation.NavigationStack.ToList();
//Then we invert it because it's from first to last and we need in the inverse order
pages.Reverse();
//Then we discard the current page
pages.RemoveAt(0);
foreach (var page in pages)
{
if (page == destination) break; //We found it.
toRemove.Add(page);
}
foreach (var rvPage in toRemove)
{
navigation.RemovePage(rvPage);
}
await Navigation.PopAsync();
}
如果你有一个想要弹出的计数,这对我来说非常有用。
for(i=1; i < 大小; i++) { 如果(设备.OS == TargetPlatform.Android) { Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 1]); } 别的 { Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]); } } 等待 Navigation.PopAsync();
这对我来说非常有效:
我设置了一个计数器并抛出了一个 DisplayAlert 来找出我需要删除多少页
var x = Navigation.NavigationStack.Count();
DisplayAlert("Page Count", x.ToString(), "OK");
然后用它来删除我需要回退的数字。
Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]);
await Navigation.PopAsync();
只需删除 2 页
Application.Current.MainPage.Navigation.RemovePage(Application.Current.MainPage.Navigation.NavigationStack[Application.Current.MainPage.Navigation.NavigationStack.Count - 2]);
Application.Current.MainPage.Navigation.PopAsync();
在 Visual Studio 2019 企业版中运行良好
这里是@Alexei Humeniy 解决方案的更新
public static async Task PopToPage<T>(INavigation navigation)
{
//First, we get the navigation stack as a list
var pages = navigation.NavigationStack.ToList();
//Then we invert it because it's from first to last and we need in the inverse order
pages.Reverse();
//Then we discard the current page
pages.RemoveAt(0);
var toRemove = new List<Page>();
var tipoPagina = typeof(T);
foreach (var page in pages)
{
if (page.GetType() == tipoPagina)
break;
toRemove.Add(page);
}
foreach (var rvPage in toRemove)
{
navigation.RemovePage(rvPage);
}
await navigation.PopAsync();
}