Context switching in Windows Phone 7

Very first let us understand what I mean by word "Context Switching" here?

Context switching in context of this post is essentially, navigate back to the page from where the application got deactivated.

Context switching in Windows Phone 7

There are three steps we need to do to perform above task

  1. Find the URL of current page while deactivating the application
  2. Save the URL in isolated storage while deactivating the application
  3. At application activating or launching set the start page of application dynamically by reading URL of the page from isolated state.

Define isolated storage setting globally in app.xaml

public IsolatedStorageSettings isoStorage = IsolatedStorageSettings.ApplicationSettings;

Find URL of current page and store in application deactivated event

You can find URL of current page in the deactivated event as below. Read it and store it in isolated storage.

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    Uri currentUri = ((App)Application.Current).RootFrame.CurrentSource;
    isoStorage["data"] = currentUri.OriginalString;
          
}


Read and set the start page in application activated event

Next step you need to do is on the application activated event

  1. Read value of current URI from isolated storage
  2. If the read value is null then set the MainPage.xaml as the start page of the application
  3. Else set the read value as the start page of the application

private void Application_Activated(object sender, ActivatedEventArgs e)

{

    string CurrentURI = (string)isoStorage["data"];
    if (CurrentURI != "")
    {
        Uri uritoNavigate = new Uri(CurrentURI, UriKind.Relative);
        ((App)Application.Current).RootFrame.Navigate(uritoNavigate);
    }
    else
    {

         Uri nUri = new Uri("/MainPage.xaml"UriKind.Relative);
        ((App)Application.Current).RootFrame.Navigate(nUri);

    }

}


You need to perform same steps in application launching event also as of application activated event.

private void Application_Launching(object sender, LaunchingEventArgs e)

{

    if (IsolatedStorageSettings.ApplicationSettings.Contains("data") == false)
    {
        isoStorage.Add("data""/MainPage.xaml");
    }
    string CurrentURI = (string)isoStorage["data"];
    if (CurrentURI != "")
    {
        Uri nUri = new Uri(CurrentURI, UriKind.Relative);

        ((App)Application.Current).RootFrame.Navigate(nUri);
    }
    else
    {

        Uri nUri = new Uri("/MainPage.xaml"UriKind.Relative);
        ((App)Application.Current).RootFrame.Navigate(nUri);

    }

}


Remove isolated storage value in application closing event

private void Application_Closing(object sender, ClosingEventArgs e)
{
isoStorage["data"] = "";
isoStorage.Remove("Data");
}


This is all you need to add in App.Xaml.cs file to perform context switching in your application.

Up Next
    Ebook Download
    View all
    Learn
    View all