【问题标题】:Add items to ComboBox at runtime?在运行时向 ComboBox 添加项目?
【发布时间】:2014-02-20 06:49:47
【问题描述】:

当我按下添加按钮(比如Name="add2labels" Click="add2labels_Click")时,我试图在运行时将项目添加到ComboBox(比如Name="labelComboBox")。但是ComboBox 无法显示我新添加的值。我错过了什么?

以下是添加按钮的事件处理程序:

private List<String> labels = new List<String>();
... ...
private void add2labels_Click(object sender, RoutedEventArgs e)
{
    labels.Add("new value");

    labelComboBox.ItemsSource = labels;
}

附:我很确定这些值已正确添加到 List&lt;String&gt; labels(其计数确实每次都增加)。


更新了可行的解决方案(3 种方式):

  1. 使用ObservableCollection(@AnatoliyNikolaev 的回答)。

    List&lt;String&gt; labels 更改为ObservableCollection&lt;String&gt; labels。并且只需要拨打labelComboBox.ItemsSource = labels; 一次。

  2. 使用Binding(@HarshanaNarangoda 的回答)。

    ItemsSource="{Binding Path=labels}" 添加到ComboBox 的属性中。

  3. 使用Refresh()(@EliranPe'er 的答案)。

    将事件处理程序更改为:

    ... ...
    labelComboBox.ItemsSource = labels;
    labelComboBox.Items.Refresh();      // new added
    

【问题讨论】:

    标签: c# wpf xaml combobox


    【解决方案1】:

    您应该使用ObservableCollection&lt;T&gt; 而不是List&lt;String&gt;

    ObservableCollection 表示一个动态数据集合,当项目被添加、移除或整个列表被刷新时provides notifications

    【讨论】:

    • 有什么区别?
    • @herohuyongtao:ObservableCollection在这种情况下,每次更改集合时都会收到通知。请参阅我的答案中的链接。
    • 所以我什至不需要使用labelComboBox.ItemsSource = labels;,对吧?
    • @herohuyongtao:足以表明ItemsSource一次并进行操作添加/删除集合,ObservableCollection本身会注意到变化。您可以通过创建一个测试项目自己验证这一点。也不需要每次labelComboBox.Items.Refresh().
    【解决方案2】:

    尝试使用labelComboBox.Items.Refresh();

    【讨论】:

      【解决方案3】:

      Combobox 有一个 display 和 value 成员,用于向组合框添加值,您需要同时指定两者。

      试试这个

      ComboboxItem item = new ComboboxItem();
      item.Text = "new value";
      item.Value = 12;
      
      labels.Items.Add(item);
      

      【讨论】:

      • 我认为Value会被自动设置。
      【解决方案4】:

      我认为您必须将 XAML 中的一些代码更改为以下代码。您必须将数据绑定到您的组合框。

      <ComboBox ItemsSource="{Binding}" Height="23" HorizontalAlignment="Left" Name="comboBox1" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-20
        • 2015-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 1970-01-01
        相关资源
        最近更新 更多