我想做的是FreezableCollection.AddRange(collectionToAdd)

时间:2012-03-24 15:50:16

标签: c# wpf collections freezable

我想做的是FreezableCollection.AddRange(collectionToAdd)

每次我添加到FreezableCollection时,都会引发一个事件并发生一些事情。现在我想要添加一个新的集合,但这次我希望FreezableCollection的 CollectionChanged事件只触发一次。

循环并添加它们会引发每个新项目的事件。

有没有办法可以在目标上添加FreezableCollection,类似于List.AddRange?

2 个答案:

答案 0 :(得分:3)

从集合派生并覆盖您想要更改的行为。我能够这样做:

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));
        }
    }

答案 1 :(得分:0)

跟进@ BobHorn的好答案,让它适用于FreezableCollection

来自document

  

此成员是显式接口成员实现。有可能   仅在将FreezableCollection实例强制转换为a时使用   INotifyCollectionChanged接口。

所以你可以通过演员来做到这一点。

(FreezableCollection as INotifyCollectionChanged).CollectionChanged += OnCollectionChanged;