【问题标题】:Synchronize a ComboBox with a List<string> [C#]将 ComboBox 与 List<string> 同步 [C#]
【发布时间】:2012-02-27 18:10:35
【问题描述】:

有什么方法可以将我的List&lt;string&gt;ComboBox 同步?

我想要的是我的 ComboBox,它会根据列表的变化自动更新它的内容。

我尝试使用 ComboBox.DataSource 属性,但这不会更新 ComboBox,它只会填充一次,然后就是这样,所以...

【问题讨论】:

    标签: c# winforms list combobox synchronization


    【解决方案1】:

    使用BindingSource 对象。

     List<string> list = new List<string>();
     BindingSource bsource=new BindingSource();
    
     //Set list dataSource
     bsource.DataSource = list;
     comboBox1.DataSource = bsource;
    
     //Now add an element via Binding object
     bsource.Add("One");
     bsource.Add("Two");
    

    或者您可以尝试使用ArrayList.Adapter 方法创建 IList 的适配器包装器。

    数组列表项;

    items=ArrayList.Adapter(comboBox1.Items);
    items.Add("one");
    

    【讨论】:

    • 它使用BindingSource 对象工作!只剩下一个问题:我使用这个 List 实例化了许多 ComboBox,所有 ComboBox 都同步在一起,所以 ...
    【解决方案2】:

    尝试用ObservableCollection&lt;string&gt; 替换您的List&lt;string&gt;

    【讨论】:

    • 你是否使用数据绑定,如果使用,请使用组合框的 ItemsSource 属性
    • 问题是我可能使用它的方式不好......你如何将它设置为 ComboBox 的数据资源?我尝试使用.DataSource,但它不起作用...如果我使用.DataBindings,则不接受该类型所以...我刚刚尝试ItemsSource,该属性不存在...
    • 好的,我们说的是 WinForms 还是 WPF?
    • 我正在使用 WinForms System.Windows.Forms.ComboBox
    • AFAIK 如果你使用 WinForms 这不起作用,你必须调用 combobox.Refresh();
    【解决方案3】:

    请查看示例:How to: Create and Bind to an ObservableCollection

    有关绑定源的更多信息:Binding Sources Overview

    更新:

    对不起,我没有提到你使用的是 Windows 窗体,所以请看问题:WinForms ComboBox data binding gotcha

    【讨论】:

      猜你喜欢
      • 2011-11-11
      • 2010-12-09
      • 2012-12-19
      • 1970-01-01
      • 2012-12-26
      • 2022-11-21
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      相关资源
      最近更新 更多