问题描述
我正在动态创建一个 ComboBox
数组,并且所有 ComboBox
的 DataSource
是一个包含一些整数的单个整数列表.但是,当我在任何一个组合框中更改一个值时说 X,然后所有其他组合值都将重置为值 X.
I am creating a ComboBox
array dynamically and the DataSource
for all the ComboBox
is a single integer list that contains some integers. But when I change a value say X in any one combo box then all other combo values get reset to value X.
情况是这样的:
- 所有组合框控件都绑定到一个列表
- 当我更改组合框的选定项时,所有其他组合框控件的选定项也会更改.
如何阻止这些行为?
推荐答案
由于您将所有组合框绑定到同一个数据源 - 单个列表 - 它们使用单个 BindingManagerBase
.
Since you are binding all combo boxes to the same data source - a single list - they are using a single BindingManagerBase
.
因此,当您从组合框中选择一项时,当前的 Position
共享绑定管理器基础更改,所有组合框都转到该位置共享数据源.
So when you choose an item from one of combo boxes, the current Position
of the shared binding manager base changes and all combo boxes goes to that position of their shared data source.
要解决这个问题,您可以将它们绑定到不同的数据源:
To solve the problem you can bind them to different data source:
您可以将它们绑定到
yourList.ToList()
或任何其他列表,例如不同的BindingList
.
You can bind them to
yourList.ToList()
or any other list for example differentBindingList<T>
.
combo1.DataSource = yourList.ToList();
combo2.DataSource = yourList.ToList();
您可以为它们使用不同的BindingSource
并将您的列表设置为BindingSource 的DataSource
You can use different BindingSource
for them and set your list as DataSource
of BindingSource
combo1.DataSource = new BindingSource { DataSource= yourList};
combo2.DataSource = new BindingSource { DataSource= yourList};
也作为另一种选择:
您可以使用不同的
BindingContext
用于您的组合框.这样,即使您将它们绑定到单个列表,它们也不再同步.
You can use different
BindingContext
for your combo boxes. This way even when you bind them to a single list, they are not sync anymore.
combo1.BindingContext = new BindingContext();
combo1.DataSource = yourList;
combo2.BindingContext = new BindingContext();
combo2.DataSource = yourList;
实际上表单的所有控件都使用共享的BindingContext
.当您将 2 个控件绑定到同一个数据源时,它们也使用相同的 BindingManagerBase
这种方式,例如,当您移动到下一条记录时,所有控件都将移动到下一条记录的绑定属性的显示值下一个记录.这与您从组合框中看到的行为相同.对使用相同 BindingManagerBase
的控件进行同步是一种理想的行为.无论如何,有时我们不需要这种行为.帖子分享了原因和解决方案.
In fact all controls of the form use a shared BindingContext
. When you bind 2 controls to a same data source, then they also use the same BindingManagerBase
this way, when you for example move to next record, all controls move to next record an show value from bound property of next record. This is the same behavior that you are seeing from your combo boxes. Being sync for controls which are using the same BindingManagerBase
is a desired behavior. Anyway sometimes we don't need such behavior. The post shares the reason and the solution.
这篇关于将多个组合框绑定到一个列表 - 问题:当我选择一个项目时,所有组合框都会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!