locked
Calling MainPage Function from Android App does not work if MainPage is NavigationPage RRS feed

  • Question

  • User396348 posted

    Help!

    In my Android Project I am trying to call a function on the MainPage like this:

    (App.Current.MainPage as MainPage)?.ProcessResults(r);

    The code compiles but when I execute the code, (App.Current.MainPage as MainPage) is null.

    In my App.xaml.cs, my constructor code looks like this:

    ``` public App() { InitializeComponent();

            MainPage = new NavigationPage(new MainPage());
        }
    

    ``` However, if I change the following line in the constructor from:

    MainPage = new NavigationPage(new MainPage());

    to: MainPage = new MainPage();

    Then (App.Current.MainPage as MainPage)?.ProcessResults(r);

    Works!

    How can I get (App.Current.MainPage as MainPage)?.ProcessResults(r); to work when MainPage = new NavigationPage(new MainPage());?

    Thanks

    Thursday, August 20, 2020 12:48 PM

Answers

  • User382871 posted

    The code compiles but when I execute the code, (App.Current.MainPage as MainPage) is null. 1.This is because you put the contentPage in the navigation stack. The MainPage will be type of NavigationPage. Try to get the navigation stack, then retrive the 'MainPage' from the stack. Because the page is set as the MainPage, it'll be at the bottom of the stack.

    Check the code: var navigationPage = App.Current.MainPage as NavigationPage; var page = navigationPage.Navigation.NavigationStack[0];

    2.You could also use MessagingCenter to call the 'ProcessResults' method of the 'MainPage' in the Android platfrom project.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Thursday, August 20, 2020 1:51 PM

All replies

  • User382871 posted

    The code compiles but when I execute the code, (App.Current.MainPage as MainPage) is null. 1.This is because you put the contentPage in the navigation stack. The MainPage will be type of NavigationPage. Try to get the navigation stack, then retrive the 'MainPage' from the stack. Because the page is set as the MainPage, it'll be at the bottom of the stack.

    Check the code: var navigationPage = App.Current.MainPage as NavigationPage; var page = navigationPage.Navigation.NavigationStack[0];

    2.You could also use MessagingCenter to call the 'ProcessResults' method of the 'MainPage' in the Android platfrom project.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Thursday, August 20, 2020 1:51 PM
  • User396348 posted

    Both solutions you provided solved my problem. I like the MessageCenter functionality better so I changed to that. Thanks!!

    Thursday, August 20, 2020 5:00 PM