1

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I thought that reassigning ItemSource will help but to my experience this is not working as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.