在运行时将项目添加到ComboBox? [英] Add items to ComboBox at runtime?

查看:94
本文介绍了在运行时将项目添加到ComboBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  private List< String>标签=新的List< String>(); 
... ...
private void add2labels_Click(对象发送者,RoutedEventArgs e)
{
labels.Add( new value);

labelComboBox.ItemsSource =标签;
}

我很确定这些值已添加到 List< String>标签(其计数每次都确实增加)。






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




  1. 使用 ObservableCollection (@ AnatoliyNikolaev的答案)。 / p>

    更改 List< String>标签 ObservableCollection< String>标签。只需一次调用 labelComboBox.ItemsSource =标签;


  2. 使用绑定(@ HarshanaNarangoda的答案)。



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


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



    将事件处理程序更改为:

      ... ... 
    labelComboBox.ItemsSource =标签;
    labelComboBox.Items.Refresh(); //新添加的



解决方案

您应使用 ObservableCollection< T> 而不是 List< String>


ObservableCollection表示一个 dynamic 数据集合,当添加,删除或刷新整个列表时,提供通知



I am trying to add items to a ComboBox (say Name="labelComboBox") at runtime when I pressed an add button (say with Name="add2labels" Click="add2labels_Click"). But the ComboBox cannot show the values I newly added. What did I miss?

The following is the event handler for the add button:

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

    labelComboBox.ItemsSource = labels;
}

P.S. I am pretty sure the values were added to List<String> labels correctly (its count did increase each time).


Updated with workable solutions (3 ways) :

  1. Use ObservableCollection (@AnatoliyNikolaev's answer).

    Change List<String> labels to ObservableCollection<String> labels. And only need to call labelComboBox.ItemsSource = labels; once in all.

  2. Use Binding (@HarshanaNarangoda's answer).

    Add ItemsSource="{Binding Path=labels}" to ComboBox's properties.

  3. Use Refresh() (@EliranPe'er's anwer).

    Change the event handler to:

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

解决方案

You should use ObservableCollection<T> instead of List<String>:

ObservableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

这篇关于在运行时将项目添加到ComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆