Jan Kowalski Jan Kowalski - 2 years ago 220
C# Question

WPF Navigate to other page

I want to just navigate between pages

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void RouteItems(object sender, RoutedEventArgs e)
{
NavigationService nav = NavigationService.GetNavigationService(this);
nav.Navigate(new ItemsPage());
}
}


GetNavigationService returns null

<Window x:Class="Special.MainWindow"
Name="Window"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Special"
mc:Ignorable="d"
Title="MainWindow" WindowState="Maximized">

<Button Content="Go" Click="RouteItems"/>
</Window>


I don't want to use other method (changing Content).

EDIT

this.NavigationService is undefined

Answer Source

You need to, first add a Frame to your Xaml:

<Grid >
      <Grid.RowDefinitions>
          <RowDefinition Height="*"/>
          <RowDefinition Height="Auto"/>
      </Grid.RowDefinitions>
   <Frame x:Name="MainFrame"></Frame>
    <Button Content="Go" Click="RouteItems" Grid.Row="1"/>

</Grid>

then after you add your xaml pages, use the MainFrame to navigate:

 private void RouteItems(object sender, RoutedEventArgs e)
    {
        MainFrame.NavigationService.Navigate(new Uri("Page1.xaml", UriKind.RelativeOrAbsolute));
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download