Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection CollectionChanged event seems not to be firing – why?

What’s wrong with this code? Clicking button1 doesn’t cause the messageBox to appear.

public partial class Form1 : Form
{
    public ObservableCollection<string> aCollection2 = new ObservableCollection<string>();
    myClass mc = new myClass();

    public Form1()
    {
        InitializeComponent();

        aCollection2.Add("a");
        aCollection2.Add("b");
    }


    private void button1_Click(object sender, EventArgs e)
    {
        mc.myCollection = aCollection2;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        mc.myCollection.Clear();
    }
}

With myClass defined:

class myClass
{
    public ObservableCollection<string> myCollection = new ObservableCollection<string>();

    public myClass()
    {
        myCollection.CollectionChanged += Changed;
    }

    void Changed(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        MessageBox.Show(myCollection.Count.ToString());
    }
}

EDIT: When I add a 3rd button with:

private void button3_Click(object sender, EventArgs e)
{
    mc.myCollection.Add("a");
}

It does show the messageBox. And so does button2. But after clicking button1 – none will fire anymore. How come?

like image 504
ispiro Avatar asked Oct 30 '11 22:10

ispiro


1 Answers

You added an event handler to the original ObservableCollection instance from your field initializer.
You never added an event handler to the new ObservableCollection instance from the form.
Since the original ObservableCollection never changes, your handler never runs.

This is one of the many reasons why collection properties should be read only (and they should be properties, not fields)

like image 196
SLaks Avatar answered Nov 15 '22 06:11

SLaks