您的位置:首页 > 其它

#UWP#导航(navigation)的实现

2017-03-11 11:30 363 查看

前言

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;
}
}


这样,我们就完整地实现了页面导航功能了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UWP