App.Current.MainPage NullReferenceException in Constructor of MainPageModel

空扰寡人 提交于 2021-01-29 02:30:01

问题


On the loading of MainPage, I am pushing another page from Constructor of MainPageModel. It throws NullReferenceException in MainPageModel. This is my code

MainPage constructor

public MainPage()
{
    InitializeComponent();
    Title = "MainPage";
    BindingContext = new MainPageViewModel(); 
}

MainPageModel constructor

public MainPageViewModel()
{
    App.Current.MainPage.Navigation.PushAsync(new HomePage()); //Exception
    //CommandMenu1 = new Command(async () => await NavigateNext());
}

How can I solve this issue?


回答1:


What probably happens is this:

public class App
{
    MainPage = new MainPage();
}

The MainPage() constructor has to be completed before it is assigned to the MainPage property of your App. Therefore, trying to access the App.Current.MainPage before then, you will get a NullReferenceException. This means you will have to find another way to achieve what you are trying to do here.




回答2:


You are trying to access MainPage in your View Model before it has been fully initialized. Instead of binding in your MainPage constructor bind in App.xaml.cs

public App() {
   InitializeComponent();

   MainPage = new MainPage();
   MainPage.BindingContext = new MainPageViewModel();

}



回答3:


Use OnAppearing() instead of MainPageViewModel() to give it time to load fully, Code :

 protected override async void OnAppearing()
    {
        App.Current.MainPage.Navigation.PushAsync(new HomePage());
    }

Hope it helps!




回答4:


You can try the code below:

await Navigation.PushAsync(new NewPage());

on New Page.Cs

InitializeComponent();
NavigationPage.SetHasBackButton(this, false);


来源:https://stackoverflow.com/questions/53263109/app-current-mainpage-nullreferenceexception-in-constructor-of-mainpagemodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!