The ObservableCollection CollectionChanged event doesn't seem to fire - why?

What is wrong with this code? Pressing button 1 does not cause a message 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();
    }
}

By defining myClass:

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 third button using:

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

It shows a messageBox. And button button2 too. But after pressing button 1 - no one will shoot anymore. Why?

+5
source share
1 answer

You have added an event handler to the source instance ObservableCollectionfrom your field initializer.
You have never added an event handler to a new instance ObservableCollectionfrom a form.
Since the source ObservableCollectionnever changes, your handler never starts.

, ( , )

+10

All Articles