简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM