I want to do this FreezableCollection.AddRange (collectionToAdd)

What I want to do is FreezableCollection.AddRange(collectionToAdd)

Every time I add to the FreezableCollection, an event fires and something happens. Now I have a new collection that I would like to add, but this time I want the CollectionChanged event from FreezableCollection to fire only once.

Looping and adding them will raise the event for each new element.

Is there a way that I can add to FreezableCollection for a goal similar to List.AddRange?

+2
source share
2 answers

Exit the collection and override the behavior you want to change. I was able to do it like this:

 public class PrestoObservableCollection<T> : ObservableCollection<T> { private bool _delayOnCollectionChangedNotification { get; set; } /// <summary> /// Add a range of IEnumerable items to the observable collection and optionally delay notification until the operation is complete. /// </summary> /// <param name="itemsToAdd"></param> public void AddRange(IEnumerable<T> itemsToAdd) { if (itemsToAdd == null) throw new ArgumentNullException("itemsToAdd"); if (itemsToAdd.Any() == false) { return; } // Nothing to add. _delayOnCollectionChangedNotification = true; try { foreach (T item in itemsToAdd) { this.Add(item); } } finally { ResetNotificationAndFireChangedEvent(); } } /// <summary> /// Clear the items in the ObservableCollection and optionally delay notification until the operation is complete. /// </summary> public void ClearItemsAndNotifyChangeOnlyWhenDone() { try { if (!this.Any()) { return; } // Nothing available to remove. _delayOnCollectionChangedNotification = true; this.Clear(); } finally { ResetNotificationAndFireChangedEvent(); } } /// <summary> /// Override the virtual OnCollectionChanged() method on the ObservableCollection class. /// </summary> /// <param name="e">Event arguments</param> protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (_delayOnCollectionChangedNotification) { return; } base.OnCollectionChanged(e); } private void ResetNotificationAndFireChangedEvent() { // Turn delay notification off and call the OnCollectionChanged() method and tell it we had a change in the collection. _delayOnCollectionChangedNotification = false; this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } 
+3
source

To keep track of @BobHorn a good answer so that it works with FreezableCollection ,

from document :

This member is an explicit implementation of the interface. It can only be used when an instance of FreezableCollection is passed to the INotifyCollectionChanged Interface.

So you can do this with the broadcast.

 (FreezableCollection as INotifyCollectionChanged).CollectionChanged += OnCollectionChanged; 
0
source

All Articles