I made a usercontrol that contains a togglebutton. When the user clicks on it, it shows a fullscreen-sized popup. I want to add the following functionality: when the user presses the hardware back button and the popup is opened, close the popup. The problem is that only the parent page of the usercontrol has backkeypress event. How can I handle this inside the usercontrol which is a reusable control? I try to avoid handling backbutton press in the page's code, so handling this like calling a method of the usercontrol from the page's OnBackKeyPress eventhandler is the last thing I'd like to do (the page is programmatically generated)...
Asked
Active
Viewed 2,532 times
1 Answers
4
The control will need to find a reference to the page somehow - either in the constructor, or by walking up the UI tree until it finds a PhoneApplicationPage
. It can then subscribe to the event itself, and unsubscribe from the event when it's closed.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
Thanks! Now I have another problem: I found the parent page, but the eventhandler is never called within my usercontrol :( parentPage = FindParentPage(this); if (parentPage != null) { parentPage.BackKeyPress += new EventHandler
(parentpage_BackKeyPress); } – Vic Oct 29 '10 at 13:15 -
@Vic: And is your `parentPage` variable definitely null? That should work absolutely fine. For the sake of testing, if you override OnBackKeyPress in your page, does that get called? – Jon Skeet Nov 02 '10 at 22:32
-
Thanks, the problem was that I cast to Page instead of MainPage, now it works perfectly :) – Vic Nov 03 '10 at 13:19
-
For anyone wanting to know how to find the `PhoneApplicationPage`, use the `VisualTreeHelper` as detailed in [this answer](http://stackoverflow.com/a/636456/199) – Brendan May 14 '13 at 15:42