1. Canceling Navigation
The OnNavigatingFrom
method offers the opportunity to cancel navigation using the NavigatingCancelEventArgs
parameter.
NavigatingCancelEventArgs
has the following properties:
- NavigationMode—An enum value that indicates the type of navigation. This value may be Back, Forward, New, or Refresh.
- Uri—The destination URI.
- Cancel—Setting this value to true cancels the navigation.
The NavigationCancelEventArgs
class subclasses CancelEventArgs
, which provides the Cancel
property. By setting this property to true
, the page can prevent the navigation from occurring, as shown in the following excerpt:
protected override void OnNavigatingFrom(
System.Windows.Navigation.NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
MessageBoxResult boxResult = MessageBox.Show(
"Leave this page?", "Question", MessageBoxButton.OKCancel);
if (boxResult != MessageBoxResult.OK)
{
e.Cancel = true;
}
}
Note
You should not attempt to cancel navigation in the OnNavigatingFrom
method when the hardware Back button is pressed. Instead, override the OnBackKeyPress
method to cancel the back key, which prevents navigation.
2. Cross-Page Communication
After navigation has occurred, an opportunity
remains for the previous page to interact with the current page from
the previous page’s OnNavigatedFrom
method. This is achieved using the Content
property of the NavigationEventArgs
, which provides the destination PhoneApplicationPage
object.
To see this in action, place a breakpoint in the OnNavigatedFrom
method. When the breakpoint is hit, notice that the page being
navigated to has already been instantiated and is provided in the Content
property of the NavigationEventArgs
(see Figure 1).
FIGURE 1 The Content
property of the NavigationEventArgs
contains the page being navigated to.
The Uri
property of the NavigationEventArgs
contains the URI of the destination page, including any query string that may be present.
Note
If navigating to an external URI, or when the app is being deactivated, the Uri
property of the OnNavigatedFrom
method’s NavigationEventArgs
is equal to app://external/.