Back with WP8 and Silverlight API, handling hardware back button was easy peasy. By default, PhoneApplicationPage
exposed an eventhandler called BackKeyPress
. Developers could chose to subscribe to this event handler and handle the back button.
<phone:PhoneApplicationPage shell:SystemTray.IsVisible="True" BackKeyPress="PhoneApplicationPage_BackKeyPress"> ... ... ... </phone:PhoneApplicationPage>
private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) { if (this.DrawingCanvas.Visibility == System.Windows.Visibility.Visible) { this.DrawingCanvas.Visibility = this.ColorSlider.Visibility = System.Windows.Visibility.Collapsed; this.piWords.IsLocked = false; e.Cancel = true; } }
As you can see, in the back key press, I check to see if certain view is being shown and if so, I hide it that rather than navigating page backstack.
That was Silverlight / WP API.. how would we do that in WP8.1 / WinPRT API ?
Windows.Phone.UI.Input namespace contains a class called HardwareButtons. just remember this is WP8.1 WinPRT API only – not supported on Windows store apps. Sadly no XAML wiring up.. lets go to codebehind and subscribe to it
public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; HardwareButtons.BackPressed += HardwareButtons_BackPressed; } void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e) { if (some_condition) { e.Handled = true; } }
That’s about it.. thank goodness I still have Dev preview documentation lying around 🙂
Thanks that was really helpful!
Thank that was indeed helpful.
I find myself NOT finding the right documentation when programming for Windows Phone 8.1, could you provide me the proper documentation or at least the url for it 🙂 even at microsoft dev some of the code there is outdated.
documentation is going downhill considering what .NET documentation on MSDN was like. you can find the documentation here https://dev.windowsphone.com/en-us/develop
HI
I am using back button in Win Silverlight
but facing error when i write the code you provided above..
DrawingCanvas, piWords, ColorSlider are unknown members..
what should i do..??? am i missing any api refrence…??
you should need anything except the event handle itself.. those bits are from something I was working on
Thanks and God bless you… It was very helpful