自定义 ObservableCollection
我对我创建的类似于 ObserverableCollection 的类有疑问。我的类基本上具有与它相同的功能,但是当将项目添加到列表中时,我向它添加了一些自动排序功能。我的问题是我的类实现了接口 INotifyCollectionChanged,以便在集合更改时通知显示我的集合的 ListView(至少这是我认为的)。每次我在集合中添加或删除时,我都会通知集合已更改,但 ListView 不会显示更改。那么我是否错过了 INotifyCollectionChanged 的解释?我应该改用 INotifyPropertyChanged 吗?对这个问题的任何帮助都会很棒!
以下是我的课程的重要部分:
public class AscendingObservableCollection<T> : ICollection<T>, IEnumerable<T>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
...
protected void OnCollectionChanged()
{
CollectionChanged.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
每当集合更改(项目添加/删除)时,我都会调用 OnCollectionChanged()。我使用 NotifyCollectionChangedAction.Reset 进行所有更改,因为我的集合是 LinkedList,并且 NotifyCollectionChangedEventArgs 构造函数需要 NotifyCollectionChangedAction.Add/Remove 标志的索引,而 LinkedList 通常没有。
我的 ListView 使用集合,使用 ItemSource 属性上的数据绑定来访问集合。
如果您需要更多代码,请告诉我。
I have a question about a class I created that is similar to the ObserverableCollection. My class basically has the same same functionality as it, but I add some automatic sorting features to it when items are added to the List. My question is my class implements the interface INotifyCollectionChanged so that the ListView, which displays my collection, is notified when the collection changes (at least this is what I thought it did). Every time I add or remove from the collection I notify the collection has changed, but the ListView doesn't display the changes. So have I miss interpreted what INotifyCollectionChanged does? Should I be using INotifyPropertyChanged instead? Any help on the question would be great!
Here are the important parts of my class:
public class AscendingObservableCollection<T> : ICollection<T>, IEnumerable<T>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
...
protected void OnCollectionChanged()
{
CollectionChanged.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
I call OnCollectionChanged() whenever the collection changes (item add/remove). I use NotifyCollectionChangedAction.Reset for all changes since my collection is a LinkedList and NotifyCollectionChangedEventArgs constructor needs an index for the NotifyCollectionChangedAction.Add/Remove flags which a LinkedList usually doesn't have.
My ListView which uses the collection uses Databinding on the ItemSource property for accessing the collection.
If you need more code let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,经过更多的调试和搜索步骤,我解决了问题。事实证明,Notify 的东西正在工作,但我的代码的其他部分有一个小错误,导致它崩溃。谢谢各位!
Ok I solved the problem after alot more step through debugging and searching. It turned out that the Notify stuff was working, but I had a small bug in the other section of my code that was causing it to break. Thanks every!