Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milleniumbug/4b685846b6a26a9f08f09f819f105c6e to your computer and use it in GitHub Desktop.
Save milleniumbug/4b685846b6a26a9f08f09f819f105c6e to your computer and use it in GitHub Desktop.
public static class ObservableCollectionExtensions
{
public static IDisposable SuppressCollectionEvents(this INotifyCollectionChanged collection,
bool fireEventWhenComplete = true)
{
return new CollectionEventSuppressor(collection, fireEventWhenComplete);
}
private class CollectionEventSuppressor : IDisposable
{
private readonly INotifyCollectionChanged _collection;
private readonly bool _raiseEventWhenComplete;
private readonly NotifyCollectionChangedEventHandler _currentListeners;
private readonly Type _type;
private readonly FieldInfo _eventField;
public CollectionEventSuppressor(INotifyCollectionChanged collection, bool raiseEventWhenComplete)
{
_collection = collection;
_raiseEventWhenComplete = raiseEventWhenComplete;
_type = collection.GetType();
_eventField = _type.GetField("CollectionChanged", BindingFlags.Instance | BindingFlags.NonPublic);
if (_eventField == null)
throw new TypeLoadException("Could not find CollectionChanged event on " + _type.FullName);
_currentListeners = GetListeners();
ClearListeners();
}
public void Dispose()
{
RestoreListeners();
if (_raiseEventWhenComplete && _currentListeners != null)
{
RaiseEvent();
}
}
private NotifyCollectionChangedEventHandler GetListeners()
{
return _eventField.GetValue(_collection) as NotifyCollectionChangedEventHandler;
}
private void ClearListeners()
{
SetListeners(null);
}
private void RestoreListeners()
{
SetListeners(_currentListeners);
}
private void SetListeners(NotifyCollectionChangedEventHandler listeners)
{
_eventField.SetValue(_collection, listeners);
}
private void RaiseEvent()
{
var eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null);
_currentListeners(_collection, eventArgs);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment