【发布时间】: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<String> labels(其计数确实每次都增加)。
更新了可行的解决方案(3 种方式):
-
使用
ObservableCollection(@AnatoliyNikolaev 的回答)。将
List<String> labels更改为ObservableCollection<String> labels。并且只需要拨打labelComboBox.ItemsSource = labels;一次。 -
使用
Binding(@HarshanaNarangoda 的回答)。将
ItemsSource="{Binding Path=labels}"添加到ComboBox的属性中。 -
使用
Refresh()(@EliranPe'er 的答案)。将事件处理程序更改为:
... ... labelComboBox.ItemsSource = labels; labelComboBox.Items.Refresh(); // new added
【问题讨论】: