2
votes

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?

1
did you checked if nav is not null when your debugging this ? and here a some Remarks when GetNavigationService returns null - Mark
You have seen right, nav in null. Do I have to initiate with "new"? - Kraenys
No, please check the link i've provided in the remarks section there is a description when the GetNavigationService-Method returns null. There's probably something wrong with the this you are handing over to the method. - Mark
This returns 2 things: WpfApplication3.MainWindow which only have "InitializeComponent();" for the moment and the second thing is my button in mainwindow.xaml Is that mean there's a conflict about what "this" mean? - Kraenys
Whats the type of your MainWindow ? Window? - Mark

1 Answers

4
votes

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));
    }