Silverlight 2: ComboBox Selection / Source Conflict

To reproduce:

1. Bind the ItemsSource to a View Model property of type List<T>, we’ll call it “EntityList”

2. User selects an option from the ComboBox.

3. Set EntityList to a new List<T>

Results:

The next time UpdateLayout is called you will get a System.ArgumentException.

System.ArgumentException: Value does not fall within the expected range.
at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at MS.Internal.XcpImports.MethodEx(DependencyObject obj, String name)
at MS.Internal.XcpImports.UIElement_UpdateLayout(UIElement element)
at System.Windows.UIElement.UpdateLayout()

Why this happens: its simple. When the SelectedItem is not null it is a reference that is pointing to an element of the IEnumerable bound to the ItemsSource. As soon as you change the reference of the ItemsSource there is a brief moment in time where the ItemsSource is null this the index that is used to obtain the reference from the IEnumerable throws an exception because the index is outside the bounds of IEnumerable.

To resolve:

1. Bind the ItemsSource to a View Model property of type List<T>, we’ll call it “EntityList”

2. User selects an option from the ComboBox.

3. Set the SelectedItem = null

3. Set EntityList to a new List<T>

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