Navigate to new page from code that doesn't derive from ContentPage

BenSchulzBenSchulz USMember ✭✭

Hi everyone,

My question isn't as simple as the title suggests.. I'm aware that I can use the navigation stack to find out the top-most page and call the navigation event on that page.

This is what I was planning on doing..

            Page currentPage;
            int index = Application.Current.MainPage.Navigation.NavigationStack.Count - 1;
            currentPage = Application.Current.MainPage.Navigation.NavigationStack[index];

        //after getting the correct page..
            //await currentPage.Navigation.PushAsync(new SomePage());

My problem is that the index is returning as -1.
I believe there's some added complexity due to my page hierarchy/structure.

My Apps main page is a LoginPage - and once the user has successfully logged in, they are pushed to a Modal page, which then has the rest of the navigation taking place from there.
await Navigation.PushModalAsync(new NavigationPage(new MainMenu()));

**How can I find the current active page (that the user is viewing) - from a class that is not inheriting from a ContentPage, when the NavigationStack includes a modal page? **

I need to do this so that my static 'helper' class (which the platform specific iOS / Android code accesses) can be passed a string for the page name, and this helper class can resolve that name, and navigate to the page if it exists. The helper class is being accessed via platform-specific implementations after an event on the phone (push notification tapped on)

Any help would be greatly appreciated!
Cheers.

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭
    I think you can only have one NavigationStack at time
  • JamesLaveryJamesLavery GBBeta, University ✭✭✭✭✭
    Using Freshmvvm you can swap between navigation stacks.

    See https://github.com/rid00z/FreshMvvm/blob/master/README.md - the section on multiple navigation services.
  • rafafiolrafafiol Member
    edited July 2018

    Soroush Khanlou wrote a blog describing a pattern he calls "The Coordinator", which is designed to move navigation logic out of the views, making it easier to delegate that logic to a class that manages workflow, and making it easier to reuse pages in multiple workflows. I wrote a an article on Medium that describes how to implement that in Xamarin.Forms. It really has helped me simplify and organize my code. I think this may help in your case, to move your navigation logic away form the dependency on ContentPage.

    The forums won't let me post a link, by you can copy and paste this:
    www.medium.com/@r_4199/xamarin-forms-navigation-using-delegates-and-coordinator-a01fb7e3c120

Sign In or Register to comment.