我使用Xamarin Forms并且我遇到问题时使用InsertPageBefore()方法和Pages的现有对象。
这是我的观看代码:
private FirstPage firstPage;
private SecondPage secondPage = new SecondPage();
private ThirdPage thirdPage = new ThirdPage();
private async void ItemSelectedMethod()
{
var root = App.NavigationPage.Navigation.NavigationStack[0];
if (SelectedItem == Items[0])
{
if (!IsFirstChoose)
{
App.NavigationPage.Navigation.InsertPageBefore(firstPage, root);
await App.NavigationPage.PopToRootAsync(false);
}
}
if (SelectedItem == Items[1])
{
App.NavigationPage.Navigation.InsertPageBefore(secondPage, root);
await App.NavigationPage.PopToRootAsync(false);
}
if (SelectedItem == Items[2])
{
App.NavigationPage.Navigation.InsertPageBefore(thirdPage, root);
await App.NavigationPage.PopToRootAsync(false);
}
IsFirstChoose = false;
rootPageViewModel.IsPresented = false;
}
它抛出异常" System.ArgumentException:'无法插入已存在于导航堆栈中的页面'"。如何在页面的现有对象之间切换?我不想在InsertPageBefore()中创建新对象。在调用InsertPageBefore():
之前,我尝试使用它代码foreach (var item in App.NavigationPage.Navigation.NavigationStack.ToList())
App.NavigationPage.Navigation.RemovePage(item);
但是它不起作用......任何人都可以帮助我吗?
答案 0 :(得分:1)
它没有与UWP合作。这里有适合你的解决方法,但你真的需要阅读如何使用Master-Detail页面。
public partial class App : Application
{
public static RootPage RootPage { get; private set; } //DON'T DO THIS,
//FIND A BETTER WAY
public App()
{
InitializeComponent();
RootPage = new RootPage();
MenuPage menuPage = new MenuPage(RootPage.vm);
RootPage.Master = menuPage;
RootPage.Detail = new NavigationPage(new MainPage());// NavigationPage;
MainPage = RootPage;
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
然后
private async void ItemSelectedMethod()
{
if (SelectedItem == Items[0])
{
App.RootPage.Detail = new NavigationPage(mainPage);
}
if (SelectedItem == Items[1])
{
App.RootPage.Detail = new NavigationPage(secondPage);
}
if (SelectedItem == Items[2])
{
App.RootPage.Detail = new NavigationPage(thirdPage);
}
rootPageViewModel.IsPresented = false;
}