WinForms ComboBox数据绑定getcha [英] WinForms ComboBox data binding gotcha
问题描述
假设您正在执行以下操作:
Assume you are doing something like the following
List<string> myitems = new List<string>
{
"Item 1",
"Item 2",
"Item 3"
};
ComboBox box = new ComboBox();
box.DataSource = myitems;
ComboBox box2 = new ComboBox();
box2.DataSource = myitems
所以现在我们有两个组合框绑定到该数组,一切都很好。但是,当您更改一个组合框的值时,它会将BOTH组合框更改为刚刚选择的组合框。
So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected.
现在,我知道数组总是通过引用传递了解到,当我学习C:D),但为什么地球上的组合框会一起变化?我不相信组合框控件是完全修改集合。
Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all.
作为一个工作,不要这样会实现预期/期望的功能
As a work around, don't this would achieve the funcionality that is expected / desired
ComboBox box = new ComboBox();
box.DataSource = myitems.ToArray();
推荐答案
这与数据绑定的设置有关在dotnet框架中,特别是 BindingContext
。在高级别上,这意味着如果您没有指定每个表单和表单的所有控件共享相同的 BindingContext
。当您设置 DataSource
属性时, ComboBox
将使用 BindingContext
获得一个包含该列表的 ConcurrenyMangager
。 ConcurrenyManager
跟踪列表中当前所选位置的内容。
This has to do with how data bindings are set up in the dotnet framework, especially the BindingContext
. On a high level it means that if you haven't specified otherwise each form and all the controls of the form share the same BindingContext
. When you are setting the DataSource
property the ComboBox
will use the BindingContext
to get a ConcurrenyMangager
that wraps the list. The ConcurrenyManager
keeps track of such things as the current selected position in the list.
当您设置第二个 ComboBox
的 DataSource
它将使用相同的 BindingContext
(表单),它将产生与上述用于设置相同的 ConcurrencyManager
的引用数据绑定。
When you set the DataSource
of the second ComboBox
it will use the same BindingContext
(the forms) which will yield a reference to the same ConcurrencyManager
as above used to set up the data bindings.
要获得更详细的解释,请参阅 BindingContext 。
To get a more detailed explanation see BindingContext.
这篇关于WinForms ComboBox数据绑定getcha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!