有没有办法暂停 ObservableCollection 的 NotifyCollectionChanged 事件?我想到如下所示:
Is there a way to pause the NotifyCollectionChanged event of an ObservableCollection? I thought something like the following:
public class PausibleObservableCollection<Message> : ObservableCollection<Message> { public bool IsBindingPaused { get; set; } protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (!IsBindingPaused) base.OnCollectionChanged(e); } }这样会暂停通知, out(但仍然添加)项目在 NotifyCollectionChangedEventArgs 内,因此在我再次启用通知时不会传递到绑定的DataGrid。
This pauses the notification indeed, but obviously the then left out (but still added) items are within the NotifyCollectionChangedEventArgs and are therefore not passed to the bound DataGrid when I enable the notification again.
为了控制这个方面,我必须提出一个集合的自定义实现吗?
Will I have to come up with a custom implementation of a collection in order to control this aspect?
推荐答案如果您不想松开任何通知,临时存储可能正常工作,以下可能会工作,但未经测试:
If you do not want to loose any notifications a temporary storage might work, the following might work but is untested:
public class PausibleObservableCollection<T> : ObservableCollection<T> { private readonly Queue<NotifyCollectionChangedEventArgs> _notificationQueue = new Queue<NotifyCollectionChangedEventArgs>(); 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.
更多推荐
暂停对绑定的ObservableCollection< T>的DataGrid的更新
发布评论