Earlier, I posted  a short article documenting a bug in Silverlight for Windows Phone’s Pivot control and demonstrating how to work around it to properly tombstone a Pivot control. Since the Pivot and Panorama controls are twin sons of different mothers, you may wonder: does the Panorama control suffer the same flaw? Well, there’s good news and bad news…but mostly good.

The good news is that you can untombstone – that is, restore the SelectedIndex property of – a Panorama control in a page’s OnNavigatedTo method. The bad news is that you can’t restore it directly, because in the Panorama control, SelectedIndex and SelectedItem are read-only properties. The following code won’t even compile:

 

protected override void OnNavigatedFrom(NavigationEventArgs e)

{

    // Save the Panorama control’s SelectedIndex in page state

    State["Index"] = PanoramaControl.SelectedIndex;

}

 

protected override void OnNavigatedTo(NavigationEventArgs e)

{

    // Restore the Panorama control’s SelectedIndex

    if (State.ContainsKey("Index"))

        PanoramaControl.SelectedIndex = (int)State["Index"];

}

 

As a rule, code that doesn’t compile doesn’t work very well. (Actually, is that true? If it doesn’t compile, you really don’t know whether it would work or not, no?)

The work-around is to use the control’s DefaultItem property, which is read/write, to restore the selected index. Here’s the code:

 

protected override void OnNavigatedFrom(NavigationEventArgs e)

{

    // Save the Panorama control’s SelectedIndex in page state

    State["Index"] = PanoramaControl.SelectedIndex;

}

 

protected override void OnNavigatedTo(NavigationEventArgs e)

{

    // Restore the Panorama control’s SelectedIndex

    if (State.ContainsKey("Index"))

        PanoramaControl.DefaultItem = PanoramaControl.Items[(int)State["Index"]];

}

 

The deeper I dig into Silverlight for Windows Phone, the more I realize that tombstoning, while conceptually easy, is fraught with pitfalls that can cost you no small amount of time. I’ll have more to say on this important subject – and more examples to share – later. Stay tuned.