简体   繁体   English

集合为空时通知观察者

[英]notifying observers when collection becomes empty

I writing console application, and it has queue collection, that used as a factory of messages. 我编写控制台应用程序,它具有队列集合,该队列集合用作消息的工厂。

Is there some way that collection will raise events when it becames empty. 有什么方法可以使集合变为空时引发事件。

I just don't want start doing pulling it by myself, checking it from time to time. 我只是不想自己做,不时检查一下。

I thought using ObservableCollection but I dont see a way to implement raising events when it's becomes empty. 我以为可以使用ObservableCollection但是当它变为空时,我看不到一种实现引发事件的方法。

Thanks for help. 感谢帮助。

ObservableCollection fires its CollectionChanged event when the contents of the collection change. 当集合的内容更改时, ObservableCollection会触发其CollectionChanged事件 Just hook that, and in your event handler, check to see if the collection's Count == 0 . 只需将其钩住,然后在事件处理程序中检查集合的Count == 0

You could inherit from ObservableCollectionEx and add your own event: 您可以继承ObservableCollectionEx并添加自己的事件:

    public class ObservableCollectionEx<T> : ObservableCollection<T>
    {
        public event EventHandler CollectionEmpty;

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (this.Count == 0)
            {
                var eventCopy = this.CollectionEmpty;
                if (eventCopy  != null)
                {
                    eventCopy(this, EventArgs.Empty);
                }
            }

            base.OnCollectionChanged(e);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM