在运行时将项添加到ComboBox?

时间:2014-02-20 06:49:47

标签: c# wpf xaml combobox

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

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

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

    labelComboBox.ItemsSource = labels;
}

P.S。我很确定这些值已正确添加到List<String> labels(每次都会增加其计数)。


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

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

    List<String> labels更改为ObservableCollection<String> labels。并且只需要一次调用labelComboBox.ItemsSource = labels;

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

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

  3. 使用Refresh()(@ EliranPe'er's anwer)。

    将事件处理程序更改为:

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

4 个答案:

答案 0 :(得分:2)

您应该使用ObservableCollection<T>代替List<String>

  

ObservableCollection表示动态数据集合,provides notifications在添加,删除项目或刷新整个列表时{。}}。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

Combobox有一个显示和值成员,可以将值添加到组合框中,您需要指定它们。

试试这个

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

labels.Items.Add(item);
相关问题