Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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. When is NavigationService created or how can I work around this?

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();
} 
like image 436
Jimmy Collins Avatar asked Aug 29 '26 18:08

Jimmy Collins


2 Answers

Peter Torr has a great blog post on the ins and outs of redirecting for the initial navigation, though for user login I'd suggest that you either use a full screen popup or have a login control on your "normal" start page and toggle visibility based on your first run condition.

like image 77
Derek Lakin Avatar answered Aug 31 '26 17:08

Derek Lakin


Add in class

    private bool m_onNavigatedToCalled = false;

In 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
            }
            );
        }
    }
like image 20
Lukasz Madon Avatar answered Aug 31 '26 17:08

Lukasz Madon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!