Along with the release bits for Windows Phone 7 came a new control called Pivot. Pivot allows you to define Pivot Items that the user can scroll through with a swipe of their finger to the left or right. The pivot control looks like this:
In this case, the pivot has two pivot items, requests (index 0) and tags (index 1). There are several posts in the intrawebs that explain how to use the pivot control. It’s pretty easy. One gotcha to think about when using the pivot is what happens if your application is interrupted (phone call, windows button, etc). When the user navigates back to your app with the back button, the pivot will display the first pivot item. I don’t like that. I want the user to go back exactly where they were. They should see the same pivot item that they were looking at when they navigated away from your app. Here’s how.
This isn’t a hard problem to solve. All we want to do is save the state of the selected index off the pivot control. Fortunately the smart guys at MS thought of this for us. We can use the PhoneApplicationService.Current.State dictionary to store the selected index when the phone navigates away from our app. Here’s the code:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
var state = PhoneApplicationService.Current.State;
if (state.ContainsKey("SelectedPivotIndex"))
{
state.Remove("SelectedPivotIndex");
}
state.Add("SelectedPivotIndex", pivot.SelectedIndex);
}
Now all we have to do is read in that state when we navigate to the page:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
var state = PhoneApplicationService.Current.State;
if (state.ContainsKey("SelectedPivotIndex"))
{
pivot.SelectedIndex = (int)state["SelectedPivotIndex"];
state.Remove("SelectedPivotIndex");
}
base.OnNavigatedTo(e);
}
I know, easy, right?