Win10开发:应用标题栏中添加返回操作
如果部署到PC看到的就是图上所示,当点击Page1上的“导航到Page2”就是跳转到Page2,点击Page2中的“←”就会回到Page1
如果部署到Mobiel或者模拟器上,就没有图上的应用标题栏,但是在Page2中点击Mobile的返回键同样可以回退到Page1
而正常情况下,PC上没有“返回键”无法回到Page1,Mobile上按了返回键就会“退出”当前程序。
实现方案:
我们需要了解SystemNavigationManager这个导航管理类(MSDN)
一共只有三个成员:
BackRequested 事件: 在用户调用系统提供的按钮、特定动作或后退导航的语音命令时发生。
AppViewBackButtonVisibility属性:指定系统 UI 中是否显示后退按钮的枚举值之一。默认为 Collapsed。
GetForCurrentView 方法:返回与当前窗口关联的 SystemNavigationManager 对象。
在App类的OnLaunched方法最后添加BackRequested事件:
SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
App_BackRequested的具体实现:
private void App_BackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
return;
// If we can go back and the event has not already been handled, do so.
if (rootFrame.CanGoBack && e.Handled == false)
{
e.Handled = true;
rootFrame.GoBack();
}
}
之后官方Demo的做法是在MainPage中将AppViewBackButtonVisibility设置为不可见,在其他Page设置为可见(如果能够返回)
这样的操作肯定没有问题,但非常的繁琐。可以采用下面的办法“偷懒”
继续在OnLaunched方法后添加下面的代码:
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; rootFrame.Navigated += OnNavigated;
OnNavigated的实现:
private void OnNavigated(object sender, NavigationEventArgs e)
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = ((Frame)sender).CanGoBack ?AppViewBackButtonVisibility.Visible :AppViewBackButtonVisibility.Collapsed;
}
OnNavigated的作用是在每次导航页面完成时判断当前页面是否能够回退,如果可以就让“返回”按钮可见,否则隐藏。
以上,就完成了目标。

浙公网安备 33010602011771号