0

Setup:

  1. There is a ComboBox that is bound to a ObservableCollection.
  2. There is a Car object in the UI. Its Color property is bound to the ComboBox's SelectedItem (the binding: <ComboBox SelectedItem="{Binding Car.Color}".../>
  3. The color list can change in the database and should be refreshed sometimes.

The problem:

When the ObservableCollection<MyColor> is refreshed (== this means that it sends a Reset inside its CollectionChanged event) the Car's Color property is set to the first item in the collection => the list is refreshed => ComboBox reloads the collection and sets its selected item to the first one in the collection => Car's color is changed to the same first item (because of the two-way binding) => problem

So in short - how can I avoid this? How can I tell on reload to take the selected item right away from the binding?

Jefim
  • 3,017
  • 4
  • 32
  • 50

1 Answers1

0

You can remove the binding while the collection changes:

var binding = comboBox.GetBindingExpression(ComboBox.SelectedItemProperty).ParentBinding;
comboBox.ClearValue(ComboBox.SelectedItemProperty);

ChangingData.Clear();
// <Rebuild>

comboBox.SetBinding(ComboBox.SelectedItemProperty, binding);
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I, personally, have a different case here, but your answer is quite good and maybe useful to some people. In my code though I had a specific case when I just refreshed the collection items themselves (instead of refreshing the whole collection). Anyway, thanks for the answer. – Jefim Jun 30 '11 at 05:26