wpf|C# Wpf 个人初学小案例---04PageDemo

1.实现效果:继承导航窗口NavigationWindow,实现从一个页面跳转至另一个页面(像浏览器页面那样)
2.运行结果(相关注释已写在代码中):
wpf|C# Wpf 个人初学小案例---04PageDemo
文章图片

3.
(1)文件结构:
wpf|C# Wpf 个人初学小案例---04PageDemo
文章图片

(2)MainWindow.xaml代码:


MainWindow.xaml.cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CH01.PageDemo { /// /// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : NavigationWindow//使继承于NavigationWindow导航窗口而不是继承于Window窗口, 因为NavigationWindow做Page界面跳转非常方便 ,可以和浏览器一样. 来回的跳转 { public MainWindow() { InitializeComponent(); } } }

(3)Page1.xaml代码:

Page1.xaml.cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CH01.PageDemo { /// /// Page1.xaml 的交互逻辑 /// public partial class Page1 : Page { public Page1() { InitializeComponent(); }private void Button_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("Page2.xaml",UriKind.Relative)); //NavigationService.Navigate方法的参数为接下来要传递到的新页面;UriKind.Relative是相对的 Uri } } }

(4)Page2.xaml代码:

【wpf|C# Wpf 个人初学小案例---04PageDemo】Page2.xaml.cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CH01.PageDemo { /// /// Page2.xaml 的交互逻辑 /// public partial class Page2 : Page { public Page2() { InitializeComponent(); }private void Button_Click(object sender, RoutedEventArgs e) { if (NavigationService.CanGoBack)//NavigationService.CanGoBack函数自动检查是否有上一页的导航记录;返回类型为bool型,如果有前一页面记录,就返回true,否则返回false { NavigationService.GoBack(); //NavigationService.GoBack函数负责跳转到前一个历史记录页面 } } } }

    推荐阅读