question

10918804 avatar image
0 Votes"
10918804 asked JassimAlRahma-9056 commented

Remove Current Page

Hi,

I am opening a ModalPage called MyPage22 from a page called MyPage11 this way:

 await App.Current.MainPage.Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(new PlaceDetails(place_id)));

How can I remove MyPage11 before opening the MyPage22?

I tried:

 async void Button_Clicked(System.Object sender, System.EventArgs e)
 {
     Navigation.RemovePage(this);
     await App.Current.MainPage.Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(new MyPage22()));
 }

but getting:

System.InvalidOperationException: Cannot remove root page when it is also the currently displayed page.


dotnet-csharpdotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JassimAlRahma-9056 commented

Hello,​

Welcome to our Microsoft Q&A platform!

System.InvalidOperationException: Cannot remove root page when it is also the currently displayed page

The page cannot be removed when it's currently displayed page. You could remove the 'MyPage11' in the OnDisAppearing() method of the 'MyPage22'. Or set the 'MyPage22' as the root page directly, which will remove the 'MyPage11' in the navigation stack.

async void Button_Clicked(System.Object sender, System.EventArgs e)
 {
     App.Current.MainPage = new MyPage22();
 }


Best Regards,

Jarvan Zhang



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

None of them is a MainPage so I don't want to set as MainPage.

How can I remove the MyPage11 from the MyPage22's OnDisappearing()?

0 Votes 0 ·

Any help with this please...

0 Votes 0 ·

Sorry for the late reply. To remove the page from the navigation stack, try using the following code.

var stack = Navigation.NavigationStack;
Navigation.RemovePage(stack[stack.Count - 2]);
0 Votes 0 ·

Thanks @JarvanZhang

That's not working for me. Getting index out of range.

I tried this as well:

https://social.msdn.microsoft.com/Forums/en-US/eb61647c-da0c-4b56-8cdc-95a0f4f62ae4/why-i-am-getting-cannot-remove-root-page-when-it-is-also-the-currently-displayed-page?forum=xamarinforms


it's working but the current page only close when I close the New page which is visible for the user, I mean if user Navigated from NewAd to NewAdGallery and then closed the NewAdGallery then he will see NewAd closing.


0 Votes 0 ·