Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

How to handle the back button on Windows Phone 7

On the windows phone 7 emulator, when the hardware back button is pressed, the default behaviour is for it to close your current application. I want to override this default behaviour so that it navigates to the previous page in my application.

After some research, it seems it should be possible to do this by overriding the OnBackKeyPress method, like so:

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

    // cancel the navigation
    e.Cancel = true;
}

However, clicking the back button still closes my application. Putting a breakpoint on the above method reveals that it is never called. I have another breakpoint on my application exit code, and this breakpoint is hit.

Is there something else I need to do to intercept the back button?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It would appear that it's not possible to override the OnBackKeyPress method to intercept the back key unless you use the Navigate method to move between pages in your application.

My previous method of navigation was to change the root visual, like:

App.Current.RootVisual = new MyPage(); 

This meant I could keep all my pages in memory so I didn't need to cache the data stored on them (some of the data is collected over the net).

Now it seems I need to actually use the Navigate method on the page frame, which creates a new instance of the page I'm navigating to.

(App.Current.RootVisual as PhoneApplicationFrame).Navigate(
                                    new Uri("/MyPage.xaml", UriKind.Relative)); 

Once I started navigating using this method, I could then override the back button handling in the way described in my question...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...