NavigationService.navigate null reference exceptio

2020-02-02 03:29发布

问题:

I'm learning WP coding and I have problem that I can't solve :/

try
 {
    NavigationService.Navigate(new Uri("/edit.xaml", UriKind.Relative));
 }
 catch (Exception ex)
 {
     MessageBox.Show(ex.Message.ToString(),"Error!",MessageBoxButton.OK);
 }

edit.xaml is in the same directory as MainPage.xaml

It throws "NullReferenceException"

回答1:

Because you get an NullReferenceException, my guess is that you are trying to call NavigationService.Navigate to early, for example in the MainPage constructor.

Instead, if you want to navigate immedietly when page is loaded for example, try doing it by overriding the OnNavigatedTo event by adding this code to the MainPage class:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
   NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
}


回答2:

Use this.... This solved my problem.

this.Loaded += (a, b) => {my code}


回答3:

This solve the problem:

(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/edit.xaml", UriKind.Relative));