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