Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding multiple ComboBoxes to the same ItemsSource causes problems

I have 2 ComboBoxes whose ItemsSource is bound to the same ObservableCollection:

public ObservableCollection<MyType> MyTypeCollection { get; set; }

I have defined 2 different SelectedItem properties which in turn are bound to the correct ComboBox.

public MyType MySelectedItem1 { get; set; }
public MyType MySelectedItem2 { get; set; }

Whenever I select an item in one of the ComboBoxes, both SelectedItem properties defined in my class are set to that selection. Both ComboBoxes are also set visually to that value.

Why is this?

I tried several things like Mode=OneWay etc, but it's not working.

Here's my XAML (trimmed down for the question):

<ComboBox SelectedItem="{Binding MySelectedItem1}"
          ItemsSource="{Binding MyTypeCollection, Mode=OneWay}"/>

<ComboBox SelectedItem="{Binding MySelectedItem2}"
          ItemsSource="{Binding MyTypeCollection, Mode=OneWay}"/>
like image 281
DeMama Avatar asked Oct 28 '14 18:10

DeMama


1 Answers

I'm guessing you have IsSynchronizedWithCurrentItem="True" on both ComboBox controls. Remove it from both, and that should solve your problem.

Setting IsSynchronizedWithCurrentItem="True" tells the ComboBox that it should keep its SelectedItem in sync with the CurrentItem in the underlying ICollectionView. Since you are binding directly to a collection, and not a collection view, both combo boxes are using the default collection view, which is a common instance shared across controls. When one of your combo boxes updates the collection view's selection, the other sees the change and updates its own selection to match it.

like image 115
Mike Strobel Avatar answered Sep 28 '22 16:09

Mike Strobel