ispiro
ispiro

Reputation: 27633

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?

Upvotes: 5

Views: 5526

Answers (1)

SLaks
SLaks

Reputation: 887225

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)

Upvotes: 10

Related Questions