Search code examples
wpfdata-bindingtwo-way

Two-way binding and a Selector


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?


Solution

  • 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);