Windows Phone 8 has been using the Silverlight stack while new Windows Phone 8.1 will be using Windows Runtimes’ XAML stack. But if you want to continue with Silverlight, it’s still possible with Windows Phone Silverlight version of templates in Visual Studio.
Let’s go by the example. Here I have 2 Windows Phone applications, one developed using Windows Phone Silverlight and the other developed using Windows Phone 8.1. In both applications, I have a button in the Main Page and when I click on the button, it will navigate to another page. And now what I need to test is clicking on hardware back button from the second screen from both these applications. Expected behavior is navigating back to the Main Page.
One way is, you can handle it for application level by implementing the Windows.Phone.UI.Input.HardwareButtons.BackPressed event in the App.xaml.
In App.xaml.cs
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
Frame frame = Window.Current.Content as Frame;
if (frame.CanGoBack)
{
e.Handled = true;
frame.GoBack();
}
}
If you want to handle it only for a specific page, you can do the following in the page level as well.
Second Page
public SecondPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}
void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
Now if you are thinking because of we have to manually handle hardware back button in Windows Phone 8.1 and since Windows Phone Silverlight handles back button automatically, Windows Phone Silverlight is good, well I don’t think so. It’s true that there are some features still which are only available in Windows Phone Silverlight and not available in Windows Phone, but Microsoft is in the process of making them available under Windows Runtime. By then it will be available for future Windows Phones. Because of this Windows Phone 8.1s’ convergence with Windows Runtime, you can develop apps for Windows Store as well as for Windows Phone having the same code base. Isn’t it just great.
I am uploading the sample code.
References: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn639128.aspx