问题
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