问题描述
我正在尝试在运行时将项目添加到 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方式):
-
使用
ObservableCollection
(@ AnatoliyNikolaev的答案)。 / p>
更改
List< String>标签
到ObservableCollection< String>标签
。只需一次调用labelComboBox.ItemsSource =标签;
。 -
使用
绑定
(@ HarshanaNarangoda的答案)。
添加
ItemsSource = {Binding Path = labels}
到ComboBox
的属性。 -
使用
Refresh()
(@ EliranPe'er的答案)。
将事件处理程序更改为:
... ...
labelComboBox.ItemsSource =标签;
labelComboBox.Items.Refresh(); //新添加的
您应使用而不是 List< String>
:
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) :
Use
ObservableCollection
(@AnatoliyNikolaev's answer).Change
List<String> labels
toObservableCollection<String> labels
. And only need to calllabelComboBox.ItemsSource = labels;
once in all.Use
Binding
(@HarshanaNarangoda's answer).Add
ItemsSource="{Binding Path=labels}"
toComboBox
's properties.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>
:
这篇关于在运行时将项目添加到ComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!