7

In Windows Phone 8.0 I used this to handle the back button:

protected override void OnBackKeyPress(CancelEventArgs e)
{
    base.OnBackKeyPress(e);        
}

This Event does not exists on the "Page" control. How can I handle a click on the back button in WP 8.1?

NGLN
  • 43,011
  • 8
  • 105
  • 200
Roman
  • 123
  • 1
  • 6

3 Answers3

3

Take a look at Windows.Phone.UI.Input.HardwareButtons.

If you add a Basic Page to your project then VS will add a NavigationHelper class to your project which helps with Navigating thru your App, you can also see in the source code that it is subscribing to Windows.Phone.UI.Input.HardwareButtons.BackPressed.


In case you want to extend handling the Back Button (managing Eventhandler queue and so on) you may take a look at this answer - the method there will help to prevent backward navigation (if you don't need it) and add some more behaviours.

Community
  • 1
  • 1
Romasz
  • 29,662
  • 13
  • 79
  • 154
  • Does it matter that the documentation states "This API is supported in native apps only" – Lukkha Coder Apr 16 '14 at 15:03
  • @Roman I've added a link to other answer which you may be interested in - helps to handle the BackButton, prevent navigation and more. – Romasz May 05 '14 at 09:16
  • @LukkhaCoder You won't be able to use it with Windows Phone 8.1 Silverlight. – Romasz May 05 '14 at 09:19
  • @Nanoc That's right, MSDN also says that. The question was about WP8.1 Runtime. – Romasz Jul 03 '14 at 15:54
  • Great tip, it can still be used in shared code when you surround the event wire up with a #if WINDOWS_PHONE_APP compiler statement – caschw Oct 27 '14 at 14:05
2

You can use Windows.Phone.UI.Input.HardwareButtons like above comment. But this event always is throwed in every page. So you can use like below example and this only is throwed in active page.


protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}

void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    e.Handled = true;
    Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
    // Navigate to a page
}

I solve my problem with this way.

hakanaltindis
  • 99
  • 1
  • 11
1

Im migrating my wp8 proyect to wp8.1 universal, so to not touch too much my code I do:

In my page base class, in the constructor, I added:

 public VBasePage()
    {
        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    } 

And then:

private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
    {
        var args = new CancelEventArgs();
        OnBackKeyPress(args);
        if (args.Cancel)
        {
            e.Handled = true;
        }
    }
protected virtual void OnBackKeyPress(CancelEventArgs e)
    {
    }

So I can use my current overrides for OnBackKeyPress method

moledj
  • 31
  • 3