Álvaro García
Álvaro García

Reputation: 19356

Is it possible to subscribe to the CollectionChanged event on an ObservableCollection?

I have an ObservableCollection and I would like to do something when the collection is changed.

private ObservableCollection<myType> _oc = new ObservableCollection<myType>();

public MyConstructor()
{
    _oc.CollectionChanged += myEventHandler();
}

private System.Collections.Specialized.NotifyCollectionChangedEventHandler myEventHandler()
{
    //myCode
}

But the code in myEventHandler is not execute.

How could I do that?

Thank so much.

Upvotes: 0

Views: 1871

Answers (1)

Laurent Jalbert Simard
Laurent Jalbert Simard

Reputation: 6329

The signature of your handler seems off. Could you try something like this:

private ObservableCollection<myType> _oc = new ObservableCollection<myType>();

public MyConstructor()
{
    _oc.CollectionChanged += CollectionChanged;
}

private void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    //myCode
}

And obviously add something to the collection so you can test the event.

_oc.Add(new myType());

Upvotes: 4

Related Questions