Silverlight 2: ComboBox Selection / Source Conflict
To reproduce:
- Bind the ItemsSource to a View Model property of type List
, we’ll call it “EntityList” - User selects an option from the ComboBox.
- Set EntityList to a new List
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:
- Bind the ItemsSource to a View Model property of type List
, we’ll call it “EntityList” - User selects an option from the ComboBox.
- Set the SelectedItem = null
- Set EntityList to a new List