Two-way binding and a Selector
Setup:
- There is a ComboBox that is bound to a ObservableCollection.
- 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}".../>
- 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?
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);
精彩评论