簡體   English   中英

如何在 WPF 中從 mainwindow.xaml 導航到 page.xaml

[英]How to navigate from mainwindow.xaml to page.xaml in WPF

我知道如何使用從一個“page.xaml”導航到另一個“page.xaml”

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

但我需要代碼從主“window.xaml”導航到“page.xaml”。

您應該有一個Page ,該Page顯示在您的Frame任何其他頁面之前。 然后可以進行通常的導航。

這是應該保留在您的Window.xaml 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 新建項目向導創建的,那么您應該已經在那里使用了此方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM