【问题标题】:Handling back button Windows 8.1 Universal app处理后退按钮 Windows 8.1 通用应用程序
【发布时间】:2014-07-03 15:25:27
【问题描述】:

我正在将我的应用从 Windows Phone 8 Silverlight 更新到 Windows 8.1 RT(我认为就是这样)。

我刚刚创建了第二个页面,当我进入并按下后退按钮时,它会退出我的应用程序,而不是返回到第一页。

我不知道为什么会这样,默认行为会到最后一页对吗?

我找不到如何覆盖后退按钮事件来进行Frame.GoBack() 调用。

这是一个开发预览错误还是我遗漏了什么?

【问题讨论】:

  • @igrali HardwareButtons 类不支持通用应用程序,只有 Windows Phone 8。link 这个问题没有解决任何问题...
  • 您应该在说某事没有解决任何问题之前检查您的事实 - 该链接表明 最低 版本是 Windows Phone 8.0。我的解决方案适用于通用应用程序,您的问题仍然是重复的。
  • 好吧,我知道你可以从 Windows 8 开始制作通用应用程序,我以为是 8.1 上的新应用,无论如何 Visual Studio 告诉我没有任何 HardwareButtons 类,有什么方法可以解决它?
  • 确保它在#if WINDOWS_PHONE_APP 里面

标签: windows-runtime windows-phone-8.1 win-universal-app


【解决方案1】:

放入第二页的构造函数:(SecondPage.xaml.cs)

Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;

然后定义事件处理函数:

    private void HardwareButtons_BackPressed( object sender, BackPressedEventArgs e )
    {
        Frame.GoBack();
        e.Handled = true;
    }

【讨论】:

  • 会不会声明e.Handled = true;在“Frame.GoBack();”之后执行?见stackoverflow.com/questions/24557713/…
  • windows 8.1 软返回键呢?
  • 如果页面没有被缓存然后重新创建,这不会造成泄漏吗?也许最好在进入时订阅并在退出时取消订阅?
  • 最好在App.xaml.cs 中执行此操作,然后先检查Frame.CanGoBack
【解决方案2】:

在通用 Windows 应用程序中,您还可以在 App.xaml.cs 文件中全局处理“后退按钮”单击。请看下面:

  1. 在 OnLaunched 方法中添加以下代码:

    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
      //..Rest of code...
    
       rootFrame.Navigated += OnNavigated;
    
    
        // Register a handler for BackRequested events and set the
        // visibility of the Back button:
    
        SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
    
        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
            rootFrame.CanGoBack  ?
            AppViewBackButtonVisibility.Visible :
            AppViewBackButtonVisibility.Collapsed;
    
        //..Rest of code...
    
    }
    

那么您应该在 App 类中添加处理程序方法的代码:

    private void OnNavigated(object sender, NavigationEventArgs e)
    {
      // Each time a navigation event occurs, update the Back button's visibility:

        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
        ((Frame)sender).CanGoBack ?
        AppViewBackButtonVisibility.Visible :
        AppViewBackButtonVisibility.Collapsed;
    }



   private void OnBackRequested(object sender, BackRequestedEventArgs e)
   {
      Frame rootFrame = Window.Current.Content as Frame;

      if (rootFrame.CanGoBack)
      {
        e.Handled = true;
        rootFrame.GoBack();
      }
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多