I am attempting to get some custom objects from the CollectionChanged event of a collection which implements INotifyCollectionChanged.
MyControl_MyCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if(e.Action == NotifyCollectionChangedAction.Add)
{
lock(e.NewItems.SyncRoot)
{
var myItems = e.NewItems.OfType<MyType>();
if(myItems.Any())
{
//do stuff
}
}
}
}
The problem I am facing is that myItems always says “Enumeration yielded no results”.
Expanding on debug e.NewItems.SyncRoot shows the following:
e.NewItems.SyncRoot | {object[1]}
|-[0] | {System.Linq.Enumerable.WhereSelectListIterator<MyType, IMyInterface>}
| |-base ...
| |-Non-public members
| |-Results View | Expanding the Results View...
| |-[0] | MyType
So clearly the data is there. What is the method for retrieving this data?
This looks like a bug in whatever is creating the
NotifyCollectionChangedEventArgsobject.NotifyCollectionChangedEventArgs has several constructors. There are two relevant ones here:
NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction, object)NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction, IList)The first describes a change on a single item. The second describes a change on a list of items.
However, the
NotifyCollectionChangedEventArgsconstructor has been called asnew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, enumerable).IEnumerable<...>does not implementIList, so the first constructor gets called when the second is the one that should be used.Do you have control over the code that raises
NotifyCollectionChanged? If so, usenew NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, enumerable.ToList())instead.