Search code examples
c#windows-phone-8nullreferenceexceptionnavigationservice

Windows Phone 8 NavigationService.Navigate throws a NullReferenceException


I am working on a C# Project for WindowsPhone 8. When the user deactivates the App (i.e. Going to the main menu) I stop some timers and save some things. This works fine. But when the user reactivates the app I want to navigate the user to a pause screen.

 NavigationService.Navigate(new Uri("/Pause.xaml", UriKind.Relative));

The Code is simple and works perfect when the app isn't deactivated. But when the user reactivates the app it throws a NullReferenceException.

I already tried several things such as:

    public void pause_for_activated()
    {
        this.Loaded += navigate_pause();
    }

    private RoutedEventHandler navigate_pause()
    {
        NavigationService.Navigate(new Uri("/Pause.xaml", UriKind.Relative));
        return navigate_pause();
    }

When I start the app without automatically navigating to the pause screen and then press a button to navigate it works. My Question is now when can I automatically navigate and how can I do this ?

In advance , I thank you already.


Solution

  • I got no answer until now, but I found a solution for me so I decided to put it here.

     Loaded += navigate_pause();
    
    
     private RoutedEventHandler navigate_pause() 
     {
            Dispatcher.BeginInvoke(() =>
            {
                ((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/Pause.xaml", UriKind.Relative));
            });
            return null;
     }