如何在 WPF 中将两个 ObservableCollections 显示为单个列表?
我有两个 ObservableCollections,例如 ObservableCollection
和 ObservableCollections
。 Cat 和 Dog 都派生自 Pet 类。我想显示所有宠物的列表。我该怎么做?我不想通过添加两个源列表中的项目来创建新的 ObservableCollection
,因为随着更多的 Cats 和 Dogs 添加到源列表中,此列表将变得过时。我可以想到两种方法:
1)创建一个“装饰器”ObservableCollection,将两个源集合保留为成员并每次迭代它们。
2) 创建一个 ObservableCollection
,它确实具有两个源集合的组合元素,但也依赖于源集合。因此,如果 Cat 被添加到 Cat 集合中,该集合就会收到通知,并将新的 Cat 添加到自身中。
有解决这个问题的标准方法吗?我不想重新发明轮子!
I have two ObservableCollections, say ObservableCollection<Cat>
and ObservableCollections<Dog>
. Cat and Dog both derive from class Pet. I want to display a list of all Pets. How do I do this? I prefer not want create a new ObservableCollection<Pet>
by adding items from the two source lists because this list will become stale as more Cats and Dogs are added to the source lists. I can think of two approaches:
1) Create a "Decorator" ObservableCollection
that keeps the two source collections as members and iterates over them every time.
2) Create an ObservableCollection<Pet>
that does have the combined elements of the two source collections, but is also dependent on the source collections. Thus if a Cat is added to the Cat collection, this collection is notified and it adds the new Cat to itself.
Is there a standard way to solve this issue? I don't want to reinvent the wheel!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 CompositeCollection 聚合多个集合并具有完整集合更改支持的项目。
编辑:
CompositeCollection
不是依赖对象,因此没有数据上下文的概念,因此绑定不起作用。如果添加绑定项或集合,则必须从代码隐藏创建集合。Use a CompositeCollection to aggregate multiple collections and items with full collection change support.
Edit:
CompositeCollection
isn't a dependency object so there no notion of data context, hence why the binding doesn't work. You have to create the collection from code behind if you add bound items or collections.