问题
I'm using Xamarin Forms (2.3.4.247) and my application is using "HamburgerMenu". To switch between pages i'm using it's code:
private FirstPage firstPage; //it's i get from the constructor
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;
}
All working good on Android and Windows 10 desktop, on Windows 10 Mobile simulator my app crashes when I switch between thirdPage and firstPage. FirstPage is root:
FirstPage firstPage = new FirstPage();
NavigationPage = new NavigationPage(firstPage);
I don't know why... Simulator don't allow debugging...
The second thing: When I update Xamarin Forms to version 2.3.5.256-pre6 my app throw exception "System.ArgumentException: 'Cannot insert page which is already in the navigation stack'"... But when I change code to:
App.NavigationPage.Navigation.InsertPageBefore(new ThirdPage(), root);
App.NavigationPage.Navigation.InsertPageBefore(new SecondPage(), root);
//etc
all working... Does anyone know why this is happening? I don't want create new objects when pages is switch...
回答1:
You have answered the question so I can only confirm this:
System.ArgumentException: 'Cannot insert page which is already in the navigation stack'
As you can see, you already have the page firstPage in App.NavigationPage.Navigation
so inserting another one makes the app crash. You just can't do it as you have explained - either you have to create a new instance or you have to remove previous instance from the stack.
来源:https://stackoverflow.com/questions/44865472/switching-between-pages-causes-crashes-on-windows-10-mobile