#UWP#导航(navigation)的实现

本文介绍了UWP应用中页面跳转和回退的实现方法。对于跳转,通过按钮点击事件触发页面切换;对于回退,利用系统BackRequested事件,结合OnBackRequested函数实现。文章详细讲解了三个步骤:Step1是在App启动时设置BackRequested事件处理器;Step2实现回退处理函数;Step3判断并控制页面回退按钮的显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

UMP应用开发中,我们经常要实验页面的跳转及回退。下面介绍他们的实现。

跳转

页面的跳转不难实现。
首先你要有一个跳转按钮,例如下面这个。

 <Page.BottomAppBar>
        <CommandBar>
            <AppBarButton x:Name="AddNewPage" Icon="add" Label="Add" Click="clickToAddNewPage"/>
        </CommandBar>
    </Page.BottomAppBar>

在这个按钮中,我们将Click事件联系到了一个C#函数

private void clickToAddNewPage(Object sender, RoutedEventArgs e)
        {
            // 此处的NewPage是另一个页面的名字
            Frame.Navigate(typeof(NewPage), "");
        }

将这个函数放到对应页面的.cs文件中,编译运行,点击这个按钮,就可以跳转到新的页面。

回退

回退有两种办法实现。
一种是类似上面的跳转方法,给每个页面设置一个回退按钮,手动将其联系到上一个页面。但这个方法有一些显而易见的缺点,①当页面过多时,设置过于繁复②当在不通设备运行时,利用不到设备特有按键,例如安卓手机的”回退”按钮
此处主要介绍第二种实现,利用系统提供的BackRequest事件来实现。

Step1

在App.xaml.css的OnLaunched函数中添加语句。

Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;

此处的意思是,当APP开始运行后,为系统的BackRequested事件添加一个处理器函数OnBackRequested.
那么,当系统收到回退请求(BackRequested)的时候,就会调用函数OnBackRequested来处理该事件。

Step2

实现函数OnBackRequested。
这个函数应该放在App.xaml.cs中的class App中,即sealed partial class App : Application{}的里面
该函数实现如下。

 private void OnBackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
                return;

            // Navigate back if possible, and if the event has not 
            // already been handled .
            if (rootFrame.CanGoBack && e.Handled == false)
            {
                e.Handled = true;
                rootFrame.GoBack();
            }
        }

大概意思是,当可以返回,并且还没有回退时,回退。

Step3

决定每个页面是否显示回退按钮。显然,如果是首页,没得回退了,我们不应该显示;而对于其他页面,是被跳转到的,可以回退到原来页面,我们应当显示回退按钮。
在每一个页面的cs文件添加以下代码,实现上述想法。

  protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            if (rootFrame.CanGoBack)
            {
                // Show UI in title bar if opted-in and in-app backstack is not empty.
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                    AppViewBackButtonVisibility.Visible;
            }
            else
            {
                // Remove the UI from the title bar if in-app back stack is empty.
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                    AppViewBackButtonVisibility.Collapsed;
            }
        }

这样,我们就完整地实现了页面导航功能了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值