This example demonstrates how to handle the Back button click. The HtmlApplication.navigatingBack event allows us to accomplish this task. However, this event handler does not provide information about the current view and its view model. Sometimes it is necessary to perform some actions before navigating. To solve this problem, we declare an additional option in the context of our application - HtmlApplication.currentViewModel. This option will store the necessary information about the current view, namely the current view model. The HtmlApplication.viewShown event handler allows you to get a view model of the shown view. We can get this view model and set it to our new option. In this case, we can access the current view model using HtmlApplication.currentViewModel and perform necessary actions in the HtmlApplication.navigatingBack event handler. Moreover, we can cancel back navigation in this event handler using the cancel option of the event handler argument as shown below:
[JScript]Application1.app.currentViewModel = null; Application1.app.viewShown.add(function(e){ Application1.app.currentViewModel = e.viewInfo.model;}); Application1.app.navigatingBack.add(function(e){if(Application1.app.currentViewModel.name == 'View1'){if(!confirm("Are you sure you want to leave View1 ?")){ e.cancel = true;return;}//Execute the required code} Application1.app.currentViewModel = null;});
Starting with 14.2, use the following code:
[JScript]Application1.app.currentViewModel = null; Application1.app.on("viewShown", function(e){ Application1.app.currentViewModel = e.viewInfo.model;}); Application1.app.on("navigatingBack", function(e){if(Application1.app.currentViewModel.name == 'View1'){if(!confirm("Are you sure you want to leave View1 ?")){ e.cancel = true;return;}//Execute the required code} Application1.app.currentViewModel = null;});
This code demonstrates how to perform actions when a user clicks the Back button on View1.
Question Comments
Added By: Paul Haffner at: 2/20/2015 10:18:14 AM
This works fine in the emulator, but when I run it on a real device running Windows Phone 8.1, the event is not triggered. Instead the app terminates immediately when the hardware back button is pressed. I am using dx 14.2.
Added By: Marion (DevExpress Support) at: 2/23/2015 1:00:27 AM @Paul,We will process this question in the context of the following thread:
T211574: Windows Phone hardware back button terminates app