Handling back button Windows 8.1 Universal app

时光毁灭记忆、已成空白 提交于 2019-12-23 21:51:09

问题


I'm updating my app from Windows Phone 8 Silverlight to Windows 8.1 RT (I think is called that).

I've just created my second page and when i go to and press the back button it goes out of my app instead of going back to first page.

I don't know why is this happening, default behaviour is going to last page right?

I can't find how to override back button event to make a Frame.GoBack() call.

Is this a dev preview bug or am I missing something?


回答1:


put into the constructor of the second page: (SecondPage.xaml.cs)

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

and then define the eventhandler function:

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



回答2:


In the Universal Windows Apps you can also handle "Back Button" click globally in the App.xaml.cs file. Please see below:

  1. In the OnLaunched method add below code:

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

Then you should add code for handlers methods in the App class:

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


来源:https://stackoverflow.com/questions/24557713/handling-back-button-windows-8-1-universal-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!