Skip to content

Instantly share code, notes, and snippets.

@lisardggY
Created October 17, 2017 11:26
Show Gist options
  • Save lisardggY/04b7a439191a3980d2d436f5c2534a5b to your computer and use it in GitHub Desktop.
Save lisardggY/04b7a439191a3980d2d436f5c2534a5b 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