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.
There are three steps we need to do to perform above task
- Find the URL of current page while deactivating the application
- Save the URL in isolated storage while deactivating the application
- 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
- Read value of current URI from isolated storage
- If the read value is null then set the MainPage.xaml as the start page of the application
- 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.