What is the equivalent to “OnBackKeyPress”

淺唱寂寞╮ 提交于 2019-12-04 04:34:22
Romasz

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.

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.

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

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