tags:

views:

34

answers:

2

Hi,

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);
    }
}
A: 

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.)

Martin
I thought that reassigning ItemSource will help but to my experience this is not working as expected.
markoniuss
+3  A: 

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

jesperll
Excellent answer, works perfectly, Thanks +++
markoniuss