2

私がやりたいのはFreezableCollection.AddRange(collectionToAdd)

FreezableCollectionに追加するたびに、イベントが発生し、何かが発生します。これで、追加したい新しいコレクションができましたが、今回はFreezableCollectionのCollectionChangedイベントを1回だけ発生させたいと思います。

ループして追加すると、新しいアイテムごとにイベントが発生します。

List.AddRangeのように、目標でFreezableCollectionにすべて追加できる方法はありますか?

4

2 に答える 2

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));
        }
    }
于 2012-03-24T17:16:41.140 に答える
0

@BobHornの良い答えをフォローアップするには、それをで動作させるためにFreezableCollection

ドキュメントから:

このメンバーは、明示的なインターフェイスメンバーの実装です。FreezableCollectionインスタンスがINotifyCollectionChangedインターフェイスにキャストされている場合にのみ使用できます。

だからあなたはキャストでそれを行うことができます。

(FreezableCollection as INotifyCollectionChanged).CollectionChanged += OnCollectionChanged;
于 2018-01-12T06:42:01.417 に答える