Search code examples
c#navigationservice

NavigationService.Navigate error


I'm quite new on C# programming and I have a problem on my code. I have created a button and applied on it an event click which open an other page of my project by the technology NavigationService.

This is the script:

private void click_login(object sender, RoutedEventArgs e)
{
    NavigationService nav = NavigationService.GetNavigationService(this); 
    nav.Navigate(new Uri("Window1.xaml", UriKind.RelativeOrAbsolute));
}

When I execute, I get this error:

The object reference is not set to an instance of an object with an InnerException null.

Can you help me please?


Solution

  • Your nav object is null, because you're trying to get the NavigationService for a WPF Window.

    But for Navigation you need a Page (Navigation Overview on MSDN)

    A Little Working example:

    Create to Page's Page1.xaml, Page2.xaml

    In the App.xaml change the StartupUri to StartupUri="Page1.xaml"

    Page1 Xaml:

     <StackPanel>
         <TextBlock Text="Hello from  Page1" />
         <Button Click="Button_Click" Content="Navigate to page 2"></Button>
     </StackPanel>
    

    Page1 cs:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService nav = NavigationService.GetNavigationService(this);
            nav.Navigate(new Uri("Page2.xaml", UriKind.RelativeOrAbsolute));
        }
    

    Page2 Xaml:

     <StackPanel>
         <TextBlock Text="Hello from  Page2" />
         <Button Click="Button_Click" Content="Navigate to page 1"></Button>
     </StackPanel>
    

    Page2 cs:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService nav = NavigationService.GetNavigationService(this);
            nav.Navigate(new Uri("Page1.xaml", UriKind.RelativeOrAbsolute));
        }