shilpashree
shilpashree

Reputation: 21

How to navigate from mainwindow.xaml to page.xaml in WPF

I know how to navigate from one "page.xaml" to another "page.xaml" using

this.NavigationService.Navigate(new Uri("Pages/Page2.xaml", UriKind.Relative));

but I need code to navigate from main "window.xaml" to "page.xaml".

Upvotes: 2

Views: 1576

Answers (1)

tomab
tomab

Reputation: 2151

You should have a Page which is displayed before any other pages into your Frame. Then the usual navigation can occur.

Here is XAML example which should stay in your Window.xaml:

<Grid Name="MainGrid">
    <Frame Name="LeftNavigationFrame"
           Grid.Column="0" >
    </Frame>
</Grid>

And in your .xaml.cs:

public partial class MainWindow : Window
{
   public MainWindow()
   {
        this.InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }
    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        LeftNavigationFrame.NavigationService.Navigate(new Uri(...));
    }
}

If you would like, here is another option, using App.xaml.cs, your main entry point for application. Navigating to first page is done in OnLaunched method and you should already have this method there if the project was created with Visual Studio New Project wizards.

protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame == null)
        {                
            rootFrame = new Frame();
            rootFrame.NavigationFailed += OnNavigationFailed;
            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                // Here you can navigate to some other pages if saved some sort of state
            }                
            Window.Current.Content = rootFrame;
        }

        if (rootFrame.Content == null)
        {
            // Replace MainPage with your desire page
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }

        Window.Current.Activate();
    }

Upvotes: 1

Related Questions