Pause the Updates to DataGrid of bound ObservableCollection

前端 未结 2 1119
[愿得一人]
[愿得一人] 2020-12-19 14:32

Is there a way to pause the NotifyCollectionChanged event of an ObservableCollection? I thought something like the following:

publ         


        
2条回答
  •  無奈伤痛
    2020-12-19 15:06

    If you do not want to loose any notifications a temporary storage might work, the following might work but is untested:

    public class PausibleObservableCollection : ObservableCollection
    {
        private readonly Queue _notificationQueue
            = new Queue();
    
        private bool _isBindingPaused = false;
        public bool IsBindingPaused
        {
            get { return _isBindingPaused; }
            set
            {
                _isBindingPaused = value;
                if (value == false)
                {
                    while (_notificationQueue.Count > 0)
                    {
                        OnCollectionChanged(_notificationQueue.Dequeue());
                    }
                }
            }
        }
    
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (!IsBindingPaused)
                base.OnCollectionChanged(e);
            else
                _notificationQueue.Enqueue(e);
        }
    }
    

    This should push every change that happens while the collection is paused into a queue, which then is emptied once the collection is set to resume.

提交回复
热议问题