2010-09-16 56 views
3

我有一个绑定到列表的组合框(Windows窗体)。它是在设计时创建的。当List内容改变时,我的代码调用一个函数来刷新数据绑定。 这对于.NET 3.5正常工作:在C#和.NET 4.0中刷新组合框数据绑定

BindingData.SuspendBinding(); 
DataSource = null; 
DataSource = BindingData; 
BindingData.ResumeBinding(); 

我已经切换到.NET 4.0,它已停止工作。特别是在通过这段代码之后,VS调试器显示BindingData.DataSource引用一个包含127个项目的列表,但ComboBox Items属性包含零个项目。

看到这个SO问题沿着一个类似的主题:ComboBox Items Count Doesn't Match DataSource

我试过了所有我能想到的东西。目前我的代码如下所示,仍然不起作用:

BindingData.SuspendBinding(); 
DataSource = null; 
DataSource = BindingData; 
BindingData.ResumeBinding(); 
BindingContext Dummy = this.BindingContext; 
Invalidate(); 
PerformLayout(); 

我试过从列表切换到BindingList,并没有帮助。我不得不根据自己的意愿从.NET 3.5切换到.NET 4.0,所以这非常令人沮丧。我确定有一个特定的序列可行。有任何想法吗?

这是怎么了,我的数据源连接到ComboBox:

private BindingSource BindingData = new BindingSource(); 

BindingData.DataSource = Nodes; 
DataSource = BindingData; 

感谢,安迪

+0

这似乎是Windows.Forms的......掉落列表标签中赞成winforms标签。 – Randolpho 2010-09-16 17:15:49

+0

如果你评论Suspen/ResumeLayout呢? – 2010-09-16 17:21:14

+0

无变化 - 列表仍为空。 – Andy 2010-09-16 17:27:13

回答

1

我解决它。我想在某些时候,我做了我认为是一个小变化,但实际上并没有。此代码从ComboBox显示时被调用移动到创建时。它还没有句柄,所以无法刷新数据绑定。

我在ComboBox.HandleCreated事件中再次刷新了数据绑定,它可以工作。

谢谢,安迪

0

为什么你暂停和恢复BindingSource?如果你只是改变你的数据源,就不会有性能上的问题。

0

根据How to: Bind a Windows Forms ComboBox or ListBox Control to Data您可以使用组合框的DisplayMember属性:

//Sample for C++ .NET: 
List<String^>^ options = gcnew List<String^>(); 
options->Add("Option 1"); 
options->Add("Option 2"); 

comboBox.DataSource = options; 
comboBox.DisplayMember = "Length";//this causes an DataSource update but the ComboBox would 
            //show an item's length instead of the item itself 
comboBox.DisplayMember = "";  //reset -> the ComboBox calls each List item's ToString 
            //member 

“长度”是指String类的公共财产。更好的做法是直接引用字符串字符的属性。 String唯一剩下的公共财产是Chars,但我无法完成工作。因此,我们将DisplayMember重置为comboBox.DisplayMember = "",导致ComboBox调用每个List项目的(a StringToString method =>问题解决。

不是字符串列表条目可以通过组合框的属性DisplayMemberValueMember处理(它们也适用于其他控件): DisplayMember & ValueMember