【问题标题】:Refreshing ComboBox Data Binding in C# and .NET 4.0在 C# 和 .NET 4.0 中刷新 ComboBox 数据绑定
【发布时间】:2011-04-13 08:12:44
【问题描述】:

我有一个绑定到列表的组合框(Windows 窗体)。它是在设计时创建的。当列表内容更改时,我的代码调用一个函数来刷新数据绑定。 这适用于 .NET 3.5

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();

我尝试从 List 切换到 BindingList,但没有帮助。我不得不违背自己的意愿从 .NET 3.5 切换到 .NET 4.0,所以这非常令人沮丧。我确信有一个特定的序列有效。有什么想法吗?

这就是我将数据源附加到 ComboBox 的方式:

private BindingSource BindingData = new BindingSource();

BindingData.DataSource = Nodes;
DataSource = BindingData;

谢谢,安迪

【问题讨论】:

  • 这似乎是 Windows.Forms... 删除列表标签以支持 winforms 标签。
  • 如果你注释掉 Suspen/ResumeLayout 怎么办?
  • 无变化 - 列表仍为空。

标签: c# winforms visual-studio-2010 combobox .net-4.0


【解决方案1】:

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

我在 ComboBox.HandleCreated 事件中再次添加了数据绑定的另一个刷新,它可以正常工作。

谢谢,安迪

【讨论】:

    【解决方案2】:

    为什么要暂停和恢复 BindingSource?如果您只是更改数据源,则不会出现性能缺陷。

    【讨论】:

      【解决方案3】:

      根据How to: Bind a Windows Forms ComboBox or ListBox Control to Data,您可以使用 ComboBox 的 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,但我无法让它工作。所以我们通过comboBox.DisplayMember = "" 重置DisplayMember,导致ComboBox 调用每个List 项的(StringToString 方法=> 问题解决了。

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

      【讨论】:

        猜你喜欢
        • 2012-01-03
        • 2010-09-30
        • 1970-01-01
        • 2011-06-23
        • 2010-10-05
        • 2011-02-16
        • 2010-10-01
        • 2021-10-03
        • 2012-02-19
        相关资源
        最近更新 更多