0

I'm trying to add a new item to the listbox everytime I press the add button but for some reason it only adds the first one, and if I press it again, it doesnt add the second one.

How I am seeing the code right now is that I create a new list named _items and then I add what ever is in my textbox everytime I press the button then I update the ItemSource aswell.

How do I make it add a new item everytime I press the AddBtn?

List<string> _items = new List<string>();


private void addBtn_Click(object sender, RoutedEventArgs e)
{
    _items.Add(recipentTextbox.Text);
    recipientLb.ItemsSource = _items;
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
John V Dole
  • 321
  • 1
  • 3
  • 11

2 Answers2

2

Try using an ObservableCollection<string> instead of List<string>. The ObservableCollection supports data binding, and will update the target property.

Clemens
  • 123,504
  • 12
  • 155
  • 268
Peter
  • 674
  • 6
  • 14
  • I used ```BindingList``` what's the difference? – John V Dole Jan 09 '17 at 19:17
  • [http://stackoverflow.com/questions/4284663/difference-between-observablecollection-and-bindinglist] – Peter Jan 09 '17 at 19:18
  • Yeah you need the ObservableCollection. Make sure you initialize it in the constructor and then only clear it never replace it as then the binding will break. – Kelly Jan 10 '17 at 02:57
0
ObservableCollection<string> _items = new ObservableCollection<string>();

//  Or whatever your constructor is
public MainWindow()
{
    recipientLb.ItemsSource = _items;
}

private void addBtn_Click(object sender, RoutedEventArgs e)
{
    _items.Add(recipentTextbox.Text);
}