Home » WPFRSS

Binding multiple combo boxes to the same list

If I bind multiple combo boxes to a list of combo box items, selecting an item in one box clears the list in the other. When I use a list that contains something other than combo box items the binding works as expected. Is this a bug or am I missing something?

Here is an example of the behavior using VS 2010 premium and .Net 4.0

<Windowx:Class="TestApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:als="clr-namespace:TestApp"Background="#CCC"Name="this"Title="Test App"><Grid><StackPanel><Label>Selecting from the second list clears the first</Label><ComboBoxWidth="150"ItemsSource="{Binding ElementName=this, Path=Broken}"/><ComboBoxWidth="150"ItemsSource="{Binding ElementName=this, Path=Broken}"Margin="0,0,0,20"/><Label>These work as expected</Label><ComboBoxWidth="150"ItemsSource="{Binding ElementName=this, Path=ThisWorks}"/><ComboBoxWidth="150"ItemsSource="{Binding ElementName=this, Path=ThisWorks}"/></StackPanel></Grid></Window>

 

namespace TestApp
{

  ///<summary>/// Interaction logic for MainWindow.xaml///</summary>publicpartialclass MainWindow : Window
  {
    ObservableCollection<ComboBoxItem> brokenList = new ObservableCollection<ComboBoxItem>();
    public ObservableCollection<ComboBoxItem> Broken
    { get { return brokenList; } }

    ObservableCollection<int> workingList = new ObservableCollection<int>();
    public ObservableCollection<int> ThisWorks
    { get { return workingList; } }

    public MainWindow()
    {
      InitializeComponent();

      for (int i = 0; i < 11; i++)
      {
        ComboBoxItem cbi = new ComboBoxItem();
        cbi.Content = i;
        brokenList.Add(cbi);

        workingList.Add(i);
      }
    
    }
  }
}
 

3 Answers Found

 

Answer 1

Pretty sure a ComboBoxItem can only have 1 parent...
 

Answer 2

What makes the combo box item behave different? If the list contains text boxes, buttons, labels or even a list box item it works. The only thing I have found to break it is the combo box item.

 

Answer 3

When the items control is rendered, it checks to see if the current item is of its item type, in case of ComboBox - ComboBoxItem, if so it does not create a new comboboxitem and just adds the item you gave it. And one item cannot have two parents, hence the wierd behavior.

In case of setting items source as collection of ints, since each item is an int and not comboboxitem, it creates a new comboboxitem and gives it the int. Hence works fine.

again no expert, but i think thats what the behavior is.

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter