Search code examples
silverlightwindows-phone-7silverlight-toolkit

ListPicker SelectedIndex Not Shown Correctly in WP7


I have a strange problem with the ListPicker element in WP7.

The Problem

Setting a ListPicker's SelectedIndex via a Binding doesn't change the default item shown after it loads.

Example

As a test, I've quickly modified Microsoft's SettingsSample to include a ListPicker. You can download it at: http://www.mediafire.com/?w0n0ymkh4dwe9b3

This is our collapsed ListPicker:

 -----------------
| Times New Roman |
 -----------------

And this is ListPicker when it's expanded:

 -----------------
| Times New Roman |
| Arial           |
| Comic Sans MS   |
 -----------------

If we select 'Arial', navigate away, then come back again, the ListPicker still shows:

 -----------------
| Times New Roman |
 -----------------

Whereas it ought to show (because the settings are saved correctly):

 -----------------
| Arial           |
 -----------------

Further Confusion

In the above example, if we click on the ListPicker, 'Arial' is actually selected (because the text for this ListBoxItem is highlighted). For some reason, it's just not shown as the default value when the control is loaded.

If we forget about the Binding approach, and instead manually set SelectedIndex to '1' in XAML, then we get the expected result when the control is loaded:

 -----------------
| Arial           |
 -----------------

Ideas?

Is there a way to update the ListPicker control to show the SelectedIndex properly when using a Binding? I guess I'm missing something obvious, but I've searched and not been able to find anything.

Thanks in advance!


Solution

  • I believe there is an outstanding bug with the ListPicker control to do with binding the selection. I think the recommended solution is to manually set a binding in the OnNavigatedTo override for the page. The following code shows how I do it for one of my apps:

            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                base.OnNavigatedTo(e);
    
                Binding pickerBinding = new Binding("DistanceUnit")
                {
                    Source = App.Current.Resources["Settings"],
                    Mode = BindingMode.TwoWay
                };
                this._distanceUnit.SetBinding(ListPicker.SelectedItemProperty, pickerBinding);
            }
    

    Alternatively, you can handle the Loaded event for the ListPicker itself and set the binding there. The previous approach is ideal if you have multiple pickers. The latter approach is more suited to the scenario when you just have a single picker.

    NOTE: I haven't checked the latest source code for the Toolkit to see if this is still an outstanding bug.