代码改变世界

C#WPF如何跳转页面 - 实践

2025-11-21 09:26  tlnshuju  阅读(0)  评论(0)    收藏  举报

在 C# WPF 中,页面跳转通常有两种主要方式:使用 NavigationWindow+Page在 Window 中切换 UserControl。以下是具体实现方法:

一、使用 NavigationWindow+Page 实现跳转(适合导航场景)

1. 创建导航窗口(NavigationWindow)

NavigationWindow 是专门用于页面导航的窗口,自带导航按钮(前进 / 后退)。

步骤 1:新建 NavigationWindow

在项目中添加一个NavigationWindow(如MainNavWindow.xaml):


 

步骤 2:设置启动窗口

App.xaml中指定启动窗口为MainNavWindow

 
2. 创建 Page 页面

新建多个Page(如Page1.xamlPage2.xaml)作为跳转目标:

Page1.xaml(包含跳转到 Page2 的按钮):


    
        
        

Page1.xaml.cs(实现跳转逻辑):

private void GoToPage2(object sender, RoutedEventArgs e) {
    // 跳转到Page2
    this.NavigationService.Navigate(new Page2());
}
3. 常用导航操作
  • 返回上一页:

    if (this.NavigationService.CanGoBack) {
        this.NavigationService.GoBack(); // 后退
    }
  • 前进到下一页:

    if (this.NavigationService.CanGoForward) {
        this.NavigationService.GoForward(); // 前进
    }
  • 刷新当前页:

    this.NavigationService.Refresh();

二、在 Window 中切换 UserControl(适合单窗口应用)

如果不需要导航历史,可在Window中通过切换UserControl实现 “页面” 切换,更灵活。

1. 创建 UserControl(模拟页面)

新建两个UserControl(如UC_Home.xamlUC_Settings.xaml):

UC_Home.xaml


    

UC_Settings.xaml


    
2. 在 Window 中切换 UserControl

在主窗口中用一个容器(如Grid)承载UserControl,通过代码动态切换:

MainWindow.xaml


    
        
        
            

MainWindow.xaml.cs(切换逻辑):

private void ShowHome(object sender, RoutedEventArgs e) {
    // 清空容器,添加首页UserControl
    ContentContainer.Children.Clear();
    ContentContainer.Children.Add(new UC_Home());
}
​
private void ShowSettings(object sender, RoutedEventArgs e) {
    // 清空容器,添加设置页UserControl
    ContentContainer.Children.Clear();
    ContentContainer.Children.Add(new UC_Settings());
}

三、两种方式的对比

方式优点缺点适用场景
NavigationWindow+Page自带导航历史(前进 / 后退)导航栏样式固定,定制性差类似浏览器的多页面导航
Window+UserControl完全自定义布局,灵活度高需手动实现导航历史(如需要)单窗口应用,如管理系统界面

根据需求选择合适的方式,小型应用推荐用Window+UserControl,需要完整导航功能时用NavigationWindow+Page