简体   繁体   English

WP7导航 - NullReferenceException

[英]WP7 Navigation - NullReferenceException

I need to navigate to a certain page the first time my app is run, to gather login details etc. I'm using IsloatedStorageSettings to save a value to determine if this is the first run of the app or not, which works fine. 我需要在第一次运行我的应用程序时导航到某个页面,以收集登录详细信息等。我正在使用IsloatedStorageSettings来保存值以确定这是否是应用程序的第一次运行,这样可以正常工作。

My problem is actually navigating to my 'first run' page when the app is run for the first time, using NavigationService, it seems NavigationService is not created at this point so is still null. 我的问题实际上是在第一次运行应用程序时导航到我的“第一次运行”页面,使用NavigationService,此时似乎没有创建NavigationService,所以仍然为null。 When is NavigationService created or how can I work around this? 什么时候创建NavigationService或者我该如何解决这个问题?

My code (in the constructor of my main page: 我的代码(在我的主页的构造函数中:

if ((bool)settings["firstRun"])
 { 
    if (NavigationService != null)
    {
        NavigationService.Navigate(new Uri("/FirstRun.xaml", UriKind.Relative));
    }
    else
    {
        MessageBox.Show("Navigation service must be null?");   //always prompts
    }                
 }
else
{
   InitializeComponent();
} 

Peter Torr有一篇很棒的博客文章,介绍了重定向初始导航的细节,但对于用户登录,我建议您使用全屏弹出窗口或在“普通”起始页面上设置登录控件并切换可见性根据您的第一次运行条件。

Add in class 在课堂上添加

    private bool m_onNavigatedToCalled = false;

In ctor 在ctor

   this.LayoutUpdated += new EventHandler(MainPage_LayoutUpdated);

Then in code 然后在代码中

    void MainPage_LayoutUpdated(object sender, EventArgs e)
    {
        if (m_onNavigatedToCalled)
        {
            m_onNavigatedToCalled = false;
            Dispatcher.BeginInvoke(() =>
            {
                if (NavigationService != null)
                {
                    MessageBox.Show("Navigation not null?"); //always prompts
                }
                else
                {
                    MessageBox.Show("Navigation service must be null?");   
                } 
                //StartApp(); do all stuff here to keep the ctor lightweight
            }
            );
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM