Home > Software engineering >  WPF - Can't use this.NavigationService.Navigate in a page that's in a Window
WPF - Can't use this.NavigationService.Navigate in a page that's in a Window

Time:11-25

I've loaded the Page1 inside a frame in a window and there is a button inside page1 that has this code:

 private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        this.NavigationService.Navigate(new Uri("NextPage.xaml", UriKind.Relative));
    }

This is the frame within MainWindow:

<Grid>
    <Frame x:Name="Main" NavigationUIVisibility="Hidden" Margin="0 0 0 0" />
</Grid>

Here is where I load Page1:

 private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Main.Navigate(new Page1());
    }

It works when I eliminate the window and directly start the app with Page1, but I want to have the window because the one Visual Studio creates automatically looks really bad. It throws the regular System.NullReferenceException: 'Object reference not set to an instance of an object.' exception when I try to use it inside the page that is loaded to a frame of MainWindow.

So, how can i navigate between pages within a window?

CodePudding user response:

You could use the Window.GetWindow to get a reference to the parent window, cast the result to your window type and then access the Frame:

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
    if (parentWindow != null)
        parentWindow.Main.NavigationService.Navigate(new Uri("NextPage.xaml", UriKind.Relative));
}
  • Related