-
-
Save milleniumbug/4b685846b6a26a9f08f09f819f105c6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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