如何处理Windows Phone 7上的后退按钮

Dav*_*001 43 windows-phone-7

在Windows Phone 7仿真器上,按下硬件后退按钮时,默认行为是关闭当前应用程序.我想覆盖此默认行为,以便导航到我的应用程序中的上一页.

经过一些研究,似乎应该可以通过覆盖OnBackKeyPress方法来实现这一点,如下所示:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    // do some stuff ...

    // cancel the navigation
    e.Cancel = true;
}
Run Code Online (Sandbox Code Playgroud)

但是,单击后退按钮仍会关闭我的应用程序.在上述方法上设置断点表明它永远不会被调用.我的应用程序退出代码上有另一个断点,并且此断点命中.

我需要做些什么才能拦截后退按钮?

Dav*_*001 29

看起来除非您使用该Navigate方法在应用程序中的页面之间移动,否则无法覆盖OnBackKeyPress方法来拦截后退键.

我之前的导航方法是更改​​根视觉,如:

App.Current.RootVisual = new MyPage(); 
Run Code Online (Sandbox Code Playgroud)

这意味着我可以将所有页面保留在内存中,因此我不需要缓存存储在其中的数据(一些数据是通过网络收集的).

现在看来我需要在页面框架上实际使用Navigate方法,这会创建我正在导航到的页面的新实例.

(App.Current.RootVisual as PhoneApplicationFrame).Navigate(
                                    new Uri("/MyPage.xaml", UriKind.Relative)); 
Run Code Online (Sandbox Code Playgroud)

一旦我开始使用这种方法导航,我就可以按照我的问题中描述的方式覆盖后退按钮处理...


Man*_*ish 23

如果您不想要默认的后退键行为,请在OnBackKeyPress的CancelEventArgs参数中设置Cancel = true.在我的页面中,我已经覆盖了后退按钮以关闭Web浏览器控件而不是导航回来.

    protected override void OnBackKeyPress(CancelEventArgs e)
    {
        if (Browser.Visibility == Visibility.Visible)
        {
            Browser.Visibility = Visibility.Collapsed;
            e.Cancel = true;
        }
    }
Run Code Online (Sandbox Code Playgroud)