开发者

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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜