Since you need to perform the action before the user changes the collection, I believe that your CollectionChangedEvent is too late (the collection has already changed).
Instead, consider creating your own collection class that derives from an ObservableCollection , and then overriding the Add (), Insert (), and Remove () methods to do additional processing before invoking the base class implementation, you should be able to find examples of this on the Internet.
Here is a sample code to get you started. This comes from the collection:
public class MyCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
public MyCollection(Collection<T> list)
: base(list)
{
}
public MyCollection()
: base()
{
}
#region INotifyCollectionChanged Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected void NotifyChanged(NotifyCollectionChangedEventArgs args)
{
NotifyCollectionChangedEventHandler handler = CollectionChanged;
if (handler != null)
{
handler(this, args);
}
}
#endregion
public new void Add(T item)
{
base.Add(item);
this.NotifyChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, base.Count-1));
this.OnPropertyChanged("Count");
}
}
source
share