暂停绑定的ObservableCollection <T>的更新到DataGrid

rdo*_*eui 4 data-binding wpf observablecollection

有没有办法暂停NotifyCollectionChanged一个ObservableCollection?我想到如下内容:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这确实暂停了通知,但显然当时我们遗漏了(但仍然添加了)项目NotifyCollectionChangedEventArgs,因此当我再次启用通知时,它们不会传递给绑定的DataGrid.

我是否必须想出一个集合的自定义实现来控制这个方面?

H.B*_*.B. 5

如果您不想丢失任何通知,临时存储可能会起作用,则以下操作可能有效但未经测试:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该推动集合暂停到队列中时发生的每个更改,然后在集合设置为恢复后清空.