MainPageModel 的构造函数中的 App.Current.MainPage NullReferenceException [英] App.Current.MainPage NullReferenceException in Constructor of MainPageModel
问题描述
在加载MainPage
时,我正在从MainPageModel
的构造函数推送另一个页面.它在 MainPageModel
中抛出 NullReferenceException
.这是我的代码
On the loading of MainPage
, I am pushing another page from Constructor of MainPageModel
. It throws NullReferenceException
in MainPageModel
. This is my code
MainPage
构造函数
MainPage
constructor
public MainPage()
{
InitializeComponent();
Title = "MainPage";
BindingContext = new MainPageViewModel();
}
MainPageModel
构造函数
MainPageModel
constructor
public MainPageViewModel()
{
App.Current.MainPage.Navigation.PushAsync(new HomePage()); //Exception
//CommandMenu1 = new Command(async () => await NavigateNext());
}
我该如何解决这个问题?
How can I solve this issue?
推荐答案
可能发生的事情是这样的:
What probably happens is this:
public class App
{
MainPage = new MainPage();
}
MainPage()
构造函数必须先完成,然后才能分配给 App
的 MainPage
属性.因此,在此之前尝试访问App.Current.MainPage
,您将得到一个NullReferenceException
.这意味着您必须找到另一种方法来实现您在此处尝试做的事情.
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.
这篇关于MainPageModel 的构造函数中的 App.Current.MainPage NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!