locked
Xamarian.Form default MasterDetail Project Application.Current.MainPage is null RRS feed

  • Question

  • User383270 posted

    I'm really trying to work my way through a Xamarian.Form app an I'm finding it difficult because the template out of the box doesn't seem to work.

    Basically on the menu I'm trying to nav to the Browse or About page. however MainPage RootPage { get => Application.Current.MainPage as MainPage; } is returning null.

    I've made no changes to this template but I do understand C# so I roughly understand the issue but I'm not aware as to why this is returning null, certainly from the starting template.

    MenuPage.xaml.xs

    using ProspectGator.Models; using System; using System.Collections.Generic;

    using Xamarin.Forms; using Xamarin.Forms.Xaml;

    namespace ProspectGator.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MenuPage : ContentPage { MainPage RootPage { get => Application.Current.MainPage as MainPage; } List menuItems; public MenuPage() { InitializeComponent();

        menuItems = new List<HomeMenuItem>
        {
            new HomeMenuItem {Id = MenuItemType.Browse, Title="Browse" },
            new HomeMenuItem {Id = MenuItemType.About, Title="About" }
        };
    
        ListViewMenu.ItemsSource = menuItems;
    
        ListViewMenu.SelectedItem = menuItems[0];
        ListViewMenu.ItemSelected += async (sender, e) =>
        {
            if (e.SelectedItem == null)
                return;
    
            var id = (int)((HomeMenuItem)e.SelectedItem).Id;
            await RootPage.NavigateFromMenu(id);
        };
    }
    

    } }

    App.xaml.cs

    using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using ProspectGator.Views;

    [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace ProspectGator { public partial class App : Application {

        public App()
        {
            InitializeComponent();
            MainPage = new NavigationPage( new  MainPage());
    
        }
    
        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
        }
    }
    

    }

    Typically I would expect this property to be set or already set but I'm not sure. I do have a MainPage.xaml.

    Saturday, March 9, 2019 2:32 PM

All replies

  • User369978 posted

    I see you set NavigationPage as MainPage in App.cs.

    Try to modify as

    Application.Current.MainPage.RootPage as MainPage;
    
    Monday, March 11, 2019 7:20 AM
  • User153793 posted

    @jlong did you make it work? I'm having the same problem

    Wednesday, June 12, 2019 6:15 PM