Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

wpf - Pause the Updates to DataGrid of bound ObservableCollection<T>

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...