【问题标题】:Windows UWP app mobile back button not workingWindows UWP 应用程序移动后退按钮不起作用
【发布时间】:2016-05-06 16:37:20
【问题描述】:

我正在使用这个有据可查的解决方案向我们的应用程序添加一个后退按钮。当应用程序初始化时,我正在这样设置:

    Windows.UI.Core.SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;

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

private void CreateNewKeyView_BackRequested(object sender, BackRequestedEventArgs e)
            {
                NavigationService.Instance.GoBack();    
            }

后退按钮显示在桌面应用程序上并按预期工作,将我们的 Frame 导航回之前的页面。

但是,在 Windows Phone 上,硬件按钮只是退出应用程序。我发现这样的代码的各个地方都表明这应该适用于移动硬件按钮,但它根本不适合我们。

【问题讨论】:

    标签: windows uwp


    【解决方案1】:

    您应该在CreateNewKeyView_BackRequested 方法中设置e.Handled = true

    【讨论】:

      【解决方案2】:

      不知道你是怎么为你的NavigationService编码的,我刚刚测试了下面的代码,它在我身边工作:

      private void CreateNewKeyView_BackRequested(object sender, BackRequestedEventArgs e)
      {
          Frame rootFrame = Window.Current.Content as Frame;
          if (rootFrame != null)
          {
              if (rootFrame.CanGoBack)
              {
                  e.Handled = true;
                  rootFrame.GoBack();
              }
          }
      }
      

      或者,对于手机,我们还使用Hardware Buttons 的特殊 API。

      可以在OnLaunched方法中判断当前使用的手机Api是否为:

      if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
      {
          Windows.Phone.UI.Input.HardwareButtons.BackPressed += OnBackPressed;
      }
      

      然后完成OnBackPressed方法:

      public void OnBackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
      {
          Frame rootFrame = Window.Current.Content as Frame;
          if (rootFrame != null)
          {
              if (rootFrame.CanGoBack)
              {
                  e.Handled = true;
                  rootFrame.GoBack();
              }
          }
      }
      

      为此,您首先需要在项目中添加Windows Mobile Extensions for the UWP 引用。

      【讨论】:

      • 那个 e.Handled = true;声明是关键。它阻止事件被进一步向上传递到响应者链到退出应用程序的操作系统。
      【解决方案3】:

      这里是

      private void CreateNewKeyView_BackRequested(object sender, BackRequestedEventArgs e) //event handle nya untuk backbutton
              {
                  var frame = ((Frame)Window.Current.Content);
                  if (frame.CanGoBack)
                  {
                      frame.GoBack();
                      e.Handled = true;
                  }
      
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多