Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Cancel the Navigation in Windows Phone Programatically

0.00/5 (No votes)
5 Oct 2012 1  
A simple tip to allow you to cancel navigation

Introduction

When you are navigating from one page to another in a Windows Phone app, there might be a scenario where you want to get a confirmation message from the user and act based on it. If the user is OK with it, then the navigation might continue or else we might have to cancel the navigation.

You can implement this kind of logic in the OnNavigatingFrom event that provides the NavigatingCancelEventArgs and includes properties like Cancel, Uri, etc.

You can use the Cancel property of the NavigatingCancelEventArgs to cancel the navigation.

Using the code

Below is a sample source code demonstrating how to cancel the navigation in Windows Phone programmatically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace PhoneApp6
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();            
        }
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
            if (MessageBox.Show("You are about to Navigate to a Different Page . " + 
                "Do you want to continue ?", "Confirmation", 
                MessageBoxButton.OKCancel)== MessageBoxResult.Cancel)
            {
                e.Cancel = true;
            }
        }
        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {
           
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {         
            NavigationService.Source = new Uri("/Page1.xaml", UriKind.Relative);
        }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here