The Silverlight 3 SelectedIndex bug

There is a Silverlight bug which bothers a lot of users worldwide – if you bing the issue you will find quite a few hits.

The Problem

The problem is simple to state. Create a combo box and bind to the SelectedIndex and ItemsSource properties and you get an out of bounds error when a value is selected.

<ComboBox SelectedIndex="{Binding Path=IndexOfCurrentValue}" ItemsSource="{Binding Values}">

One of the sources that describe the problem is http://www.lhotka.net/weblog/SilverlightComboBoxControlAndDataBinding.aspx. This post includes a work around but I wanted to find a simpler solution.

I asked the Silverlight product team and the answer was that this bug is very unfortunate, but that it may not be trivial to fix.

In my repro project, I bound SelectedIndex before binding ItemsSource, so when the binding engine sets the SelectedIndex property, items are not set yet and the value 0 is not correct.

The Solution

The workaround is simple; simply switch the order of bindings in XAML and bind ItemsSource before binding SelectedIndex.

This is a reported bug and it is still open at the time of writing this. I hope it will be fixed by Silverlight 4.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s