作者:李波2602884584 | 来源:互联网 | 2023-09-18 22:32
在开始学习WPF时,一开始对WPF的Window,Page,UserControl感到很迷惑。不知道什么时候该使用哪一个。下面简单介绍一下这三者的区别。Window:故名思意,桌面
在开始学习WPF时,一开始对WPF的Window, Page, UserControl感到很迷惑。不知道什么时候该使用哪一个。下面简单介绍一下这三者的区别。
Window:故名思意,桌面程序的窗体。在WPF桌面应用中,我通常会只用一个主窗体,然后将不同的操作单元封装在不同的UserControl中,根据用户的操作展现不同的UserControl;
Page:Page需要承载在窗体中,通过Navigation进行不同Page的切换,也是本篇博客中需要讲到的;
UserControl:封装一些可以重复使用的功能。
在这篇博客中将介绍WPF导航应用。WPF Navigation实现在不同Page之间的切换。
我们需要在NavigationWindow或者Frame中承载Page,首先看NavigationWindow
新建WelcomePage,然后设置NavigationWindow的Source为WelcomePage
Source="WelcomePage.xaml"
Title="MainWindow" >
WelcomePage.xaml:
运行效果:

再新建一个GreetingPage.xaml,我们在WelcomePage上添加一个Button,点击Button时跳转到GreetingPage.xaml,在GreetingPage上也有一个Button,点击返回到WelcomePage。
WelcomePage.xaml
Code Behind:
private void GoForwardButton_Click(object sender, RoutedEventArgs e)
{
if (this.NavigationService.CanGoForward)
{
this.NavigationService.GoForward();
}
else
{
//GreetingPage greeting = new GreetingPage();
//this.NavigationService.Navigate(greeting);
this.NavigationService.Navigate(new Uri("pack://application:,,,/GreetingPage.xaml"));
}
}
导航时,可以传递GreetingPage.xaml地址,也可以是GreetingPage对象。可以在 if (this.NavigationService.CanGoForward) 加一个断点,在从GreetingPage返回到WelcomePage后,再次点击Go Forward按钮时,直接使用this.NavigationService.GoForward()这句代码进行了导航,这是因为导航发生后,会在NavigationService中会记录导航记录。
GreetingPage.xaml:
Code Behind:
private void GoBackButton_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.GoBack();
}
运行效果:

可以在导航时传递参数。然后再NavigationWindow中获取。例如:
GreetingPage greeting = new GreetingPage();
this.NavigationService.Navigate(greeting,"This is a test message.");
在MainWindow中,
public MainWindow()
{
InitializeComponent();
this.NavigationService.LoadCompleted += NavigationService_LoadCompleted;
}
private void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
if(e.ExtraData != null)
{
// Do something here...
}
}
上面提到的Frame也可以作为Page的承载。和NavigationWindow的区别在于NavigationWindow是全局翻页,Frame是局部翻页。
运行效果:

这篇博客就到这里了,代码点击这里下载。
感谢您的阅读。