markoniuss
markoniuss

Reputation: 451

WPF Listbox - data binding problem

I have this problem, when I run application I see listbox with items "red", "blue", "yellow". But when I type "black" to textBox1 and press Button1 item is not added. Any idea why?

 public partial class Window1 : Window
{
    private static ArrayList myItems = new ArrayList();
    public Window1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = myItems;
        myItems.Add("red");
        myItems.Add("blue");
        myItems.Add("yellow");   
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        myItems.Add(textBox1.Text);
    }
}

Upvotes: 1

Views: 286

Answers (2)

Jesper Larsen-Ledet
Jesper Larsen-Ledet

Reputation: 6723

You should replace the ArrayList with an ObservableCollection<string> which will communicate to the ListBox when its contents change.

Upvotes: 3

Martin Hennings
Martin Hennings

Reputation: 16846

This is because the view (the listbox in this case) is not informed about the change.

You should either implement INotifyProperyChanged or simply reset the itemsSource:

private void button1_Click(object sender, RoutedEventArgs e)
{
    myItems.Add(textBox1.Text);
    // refresh:
    listBox1.ItemsSource = myItems;
}

(Although using OnPropertyChanged is better practice for sure.)

Upvotes: 0

Related Questions