C#的ObservableCollection OnCollectionChanged不费一枪项目更改时 [英] C# ObservableCollection OnCollectionChanged not firing when item changes

查看:2237
本文介绍了C#的ObservableCollection OnCollectionChanged不费一枪项目更改时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从MSDN约OnCollectionChanged:当一个项目被添加,删除,更改后发生,移动或整个列表刷新

From the MSDN about OnCollectionChanged: "Occurs when an item is added, removed, changed, moved, or the entire list is refreshed."

我改变一个属性附加到驻留在我的收藏的OBJ,但OnCollectionChanged不会被解雇。我在obj的类实现INotifyPropertyChanged的。

I'm changing a property attached to an obj that resides in my collection, but OnCollectionChanged isn't fired. I am implementing iNotifyPropertyChanged on the obj class.

public class ObservableBatchCollection : ObservableCollection<BatchData>
    {
        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if(e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (BatchData item in e.NewItems)
                {

                }
            }
            base.OnCollectionChanged(e);
        }

        public ObservableBatchCollection(IEnumerable<BatchData> items)
            : base(items)
        {

        }
}

对于我来说,读取时集合中的一个项目更改,如的属性对象,此事件应激发。这不,但是。我希望能够在需要时,知道什么时候在我的定义集合改变的项目,所以我可以在其上进行计算。

To me, that reads that when an item in the collection is changed, such as a property of the object, that this event should fire. It's not, however. I want to be able to know when an item in my custom collection changes so I can perform a calculation on it, if needed.

有什么想法?

推荐答案

的ObservableCollection< ; T> 引发事件,只有当集合本身更改的。包含有突变其内部状态的集合中的项目还没有改变集合的结构和的ObservableCollection< T> 将不会报告它

ObservableCollection<T> raises events only when the collection itself changes. An item contained in the collection that has its internal state mutated has not altered the structure of the collection, and ObservableCollection<T> will not report it.

一种选择是继承的ObservableCollection< T> 和订阅每个项目的 OnPropertyChanged 当它被添加的事件。在该处理程序中,你可以提高或者是自定义事件,或退回到收藏自己的PropertyChanged 事件。请注意,如果你走这条路,你应该增加一个通用的限制,使 T:INotifyPropertyChanged的

One option is to subclass ObservableCollection<T> and subscribe to each item's OnPropertyChanged event when it is added. In that handler, you can raise either a custom event, or fall back to the collection's own PropertyChanged event. Note that if you do go this route, you should add a generic constraint so that T : INotifyPropertyChanged.

这篇关于C#的ObservableCollection OnCollectionChanged不费一枪项目更改时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆