C# ObservableCollection OnCollectionChanged 在项目更改时不会触发
来自 MSDN 关于 OnCollectionChanged 的内容:“在添加、删除、更改、移动项目或刷新整个列表时发生。”
我正在更改附加到位于我的集合中的 obj 的属性,但 OnCollectionChanged 未触发。我正在 obj 类上实现 iNotifyPropertyChanged。
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)
{
}
}
对我来说,这意味着当集合中的某个项目发生更改(例如对象的属性)时,应该触发此事件。然而事实并非如此。我希望能够知道自定义集合中的项目何时发生变化,以便在需要时对其执行计算。
有什么想法吗?
From the MSDN about OnCollectionChanged: "Occurs when an item is added, removed, changed, moved, or the entire list is refreshed."
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.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ObservableCollection
仅当集合本身发生更改时才会引发事件。集合中包含的内部状态发生变化的项目并未改变集合的结构,并且ObservableCollection
不会报告它。一种选择是子类化
ObservableCollection
并在添加每个项目时订阅其OnPropertyChanged
事件。在该处理程序中,您可以引发自定义事件,也可以回退到集合自己的PropertyChanged
事件。请注意,如果您确实采用此路线,则应添加通用约束,以便T : INotifyPropertyChanged
。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, andObservableCollection<T>
will not report it.One option is to subclass
ObservableCollection<T>
and subscribe to each item'sOnPropertyChanged
event when it is added. In that handler, you can raise either a custom event, or fall back to the collection's ownPropertyChanged
event. Note that if you do go this route, you should add a generic constraint so thatT : INotifyPropertyChanged
.