The Panorama control is certainly one of the most interesting controls available on Windows Phone 7 toolset, unfortunately it has a defect that is evident during Tombstoning or when you navigate to a page containing a Panorama and try to set its initial view to an item other than the first one.
To better understand what the problem is, let’s start with this page:
that has following code associated in order to properly handle its tombstoning:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
this.State["InitialIndex"] = MyPano.SelectedIndex;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (this.State.ContainsKey("InitialIndex"))
{
MyPano.DefaultItem = MyPano.Items[(int)this.State["InitialIndex"]];
this.State.Remove("InitialIndex");
}
}
Let’s now cause application deactivation by pressing the Tombstone button that invokes a SearchTask:
|
While on Search page, let’s press Back button to return to our application.
Final result is visible on the right: Item is positioned accordingly but Title and Background not, clearly not an optimal result.
|
|
Enter SmartPanorama: A control derived from Panorama that adds a InitialIndex property through which you can easily restore initial position.
The code for a correct restoring becomes:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
this.State["InitialIndex"] = MyPano.SelectedIndex;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (this.State.ContainsKey("InitialIndex"))
{
MyPano.InitialIndex = (int)this.State["InitialIndex"];
this.State.Remove("InitialIndex");
}
}
Source code is available here so I won’t go into details, just a few clarifications:
- Code contains a little black magic that depends of some missing information and from what I saw using Reflector.
- Implementation isn’t perfect, there’s a little artifact when you left scroll the control after last PivotItem has been restored (if you find a better solution let me know, I’m all ears)
- InitialIndex is to be used exclusively to restore the initial item, is not to be intended as a way to dynamically change the item at runtime.
As always: The software is provided “as is”, without any warranty.
Enjoy a “smarter panoraming”