3

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
    
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174

4 Answers4

3

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.

costrom
  • 187
  • 1
  • 2
  • 13
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
  • What are the differences? – herohuyongtao Feb 20 '14 at 06:53
  • 1
    @herohuyongtao: `ObservableCollection` in this situation will be notified every time a change collection. Please see the link in my answer. – Anatoliy Nikolaev Feb 20 '14 at 06:56
  • So I don't even need to use `labelComboBox.ItemsSource = labels;`, right? – herohuyongtao Feb 20 '14 at 07:02
  • 1
    @herohuyongtao: Enough to indicate `ItemsSource` once and conduct operations to add / remove the collection, the `ObservableCollection` itself will notice changes. You can verify this yourself by creating a test project. Also do not need cause every time `labelComboBox.Items.Refresh()`. – Anatoliy Nikolaev Feb 20 '14 at 07:07
1

Try using labelComboBox.Items.Refresh();

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
Eliran Pe'er
  • 2,569
  • 3
  • 22
  • 33
1

Combobox has a display and value member to add values to combo-box you need to specify both.

try this

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

labels.Items.Add(item);
Aftab Ahmed
  • 1,727
  • 11
  • 15
1

I think You have to change some code in XAML to following.You have to bind data to your Combo Box.

<ComboBox ItemsSource="{Binding}" Height="23" HorizontalAlignment="Left" Name="comboBox1" />
Harshana Narangoda
  • 775
  • 1
  • 8
  • 23