smile908

导航

.net framework4.7.2 不同页面之间的跳转

首先,我们得新建一个新的.net framework 项目,系统会默认生成两个xaml文件,分别是App.xaml和mainWindow.xaml

Window:故名思意,桌面程序的窗体。在WPF桌面应用中,我通常会只用一个主窗体,然后将不同的操作单元封装在不同的UserControl中,根据用户的操作展现不同的UserControl;

Page:Page需要承载在窗体中,通过Navigation进行不同Page的切换,也是本篇博客中需要讲到的;

UserControl:封装一些可以重复使用的功能。

在这篇博客中将介绍WPF导航应用。WPF Navigation实现在不同Page之间的切换。

我们需要在NavigationWindow或者Frame中承载Page,首先看NavigationWindow

新建WelcomePage,然后设置NavigationWindow的Source为WelcomePage

 

 

 注意:在这里,我们将mainWindow的根节点Window改成了NavigationWindow,所以我们在mainWindow.xaml的对应界面mainWindow.xaml.cs

文件也要做出更改,如下。(主要将MainWindow的父类对应的改一下)

 

 接下来,我们分别创建两个页面(Page),分别是WelcomePage和GreetingPage,刚刚我们在Mainwindow里面指定了source为WelcomePage

说明我们的主界面就是welcomePage,我们将从welcomePage界面向GreetingPage页面经行跳转,然后反之跳转回来,这是我们实现的主要功能

 

 

首先我们看一下WelcomePage的界面设计和逻辑结构,页面很简单,一个文本和一个按钮组成

<Page x:Class="WpfApp2.WelcomePage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="WelcomePage">

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>

<TextBlock Text="hello Avecle" HorizontalAlignment="Center"
VerticalAlignment="Center" FontSize="24"
FontWeight="Bold" Background="red"
/>

<Button Grid.Row="1" Content="forward" Background="green"
Margin="0 10" Click="Button_forward" />
</Grid>
</Page>

 

接下来是WelcomePage的逻辑部分,我们来实现按钮的逻辑功能

private void Button_forward(object sender, RoutedEventArgs e)
{
if (this.NavigationService.CanGoForward)
{
this.NavigationService.GoForward();
}
else
{
this.NavigationService.Navigate(new Uri("pack://application:,,,/GreetingPage.xaml"));
}
}

 

下面是Greeting的页面设计和逻辑部分设计,基本和WelcomePage没用区别

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>

<TextBlock Text="Go Back" FontSize="24" HorizontalAlignment="Center"/>

<Button Margin="0 10" Content="go back" HorizontalAlignment="Center"
Click="Button_GoBack" Grid.Row="1"/>
</Grid>

private void Button_GoBack(object sender, RoutedEventArgs e)
{
NavigationService temp = this.NavigationService;
if (temp.CanGoBack)
{
temp.GoBack();
}
temp.Navigate(new Uri("pack://application:,,,/WelcomePage.xaml"));
}

 

代码部分就结束了,我们来看以下实现的效果

 

 我们点击forword按钮就可以实现页面的跳转

 

 我们就跳转到了第二个界面,在这个页面,我们想返回到第一个页面,可以点击按钮也可以点击左上角的回退按钮。

posted on 2023-01-06 14:22  smile908  阅读(137)  评论(0编辑  收藏  举报