Binding a DataTable (or List) to two Combo Boxes
I have a DataTable
(or Generic List) that I want to bin开发者_开发知识库d to 2 ComboBox
. If I bind it when one ComboBox
changes, the other ComboBox
changes too to the first ComboBox
value.
How can I separate them?
I've created another DataTable
and assigned the main DataTable
to it but the problem still remains.
Since you are refering same object to both combobox when one changes other also changes
DataTable dt;
combobox1.DataSource=dt;
DataTable dt2;
dt2 = dt.Copy();
combobox2.DataSource=dt2;
It looks like you bound the SelectedItem properties of your two Comboboxes to the same property. If you want to select different items according to your comboboxes, you should use different properties:
<ComboBox ItemSource="{Binding List}" SeletectedItem="{Binding SelectedItem1, Mode=TwoWay}"/>
<ComboBox ItemSource="{Binding List}" SeletectedItem="{Binding SelectedItem2, Mode=TwoWay}"/>
The problem is that just creating a new DataTable (or List) variable and assigning the existing list to it doesn't create a new one. It just creates another reference that points to the same one. So you have don't have two of the same thing, you have one thing that you can get to in two different ways. It's a subtle difficulty that often trips people up. :)
The Clone() method that NDC mentioned is one answer. For Lists you can also use ToArray() to make an array and bind that (as the Array won't have the same problems).
精彩评论