如何在WPF中从mainwindow.xaml导航到page.xaml

时间:2015-09-23 06:42:59

标签: c# wpf

我知道如何从一个" page.xaml"到另一个" page.xaml"使用

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

但我需要代码从main" window.xaml"到" page.xaml"。

1 个答案:

答案 0 :(得分:1)

您应该在Page的任何其他页面之前显示Frame。然后可以进行常规导航。

以下是XAML示例,该示例应保留在Window.xaml

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

在你的.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(...));
    }
}

如果您愿意,可以使用App.xaml.cs作为申请的主要入口点,这是另一种选择。导航到第一页是在OnLaunched方法中完成的,如果项目是使用Visual Studio New Project向导创建的,那么您应该已经有了这个方法。

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();
    }
相关问题