Skip to content

December 14, 2010

2

Getting Around Pivot Control SelectedIndex Bug

For those of you not aware, there’s a bug in the WP7 Pivot control. It crashes if you try and set the SelectedIndex to 2. Hopefully, you’ve encountered this during testing and found this trying to solve it. Hopefully it’ll just be fixed in a future update, but that doesn’t help now.

I tried a few things, but for Suitor 2 landed on the following solution as the simplest. The only impact it has is that your first Pivot page will display briefly before it pans to the one you desired to set programmatically. All you need to do is rig up the “Loaded” event on your Pivot control. Then you can dispatch the call to change the index, like so:

private void Pivot_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
    Dispatcher.BeginInvoke(() =>
    {
        try
        {
            pivotControl.SelectedIndex = myIndex;
        }
        catch (Exception ex)
        {
            // Feel free to do more here, but it's not required.  
            // We just need to ignore the first error as this event 
            // gets fired multiple times.
            ;
        }
    });
}

The behavior I noticed (which was part of my original problem while investigating) is that this event is called multiple times, it fails the first time due to the bug. That’s why we need to use the try/catch and ignore it. Once the control is properly loaded, the event fires again and is able to properly set the index, and thus everything starts working again.

Hope this helps someone; if so, just drop a comment.

2 Comments
  1. Edwin
    Dec 19 2010

    Thanks a lot!
    I got my problem solved!

Trackbacks & Pingbacks

  1. 芒果乾

Comments are closed.