合并的ObservableCollection [英] Merged ObservableCollection
问题描述
我有两个ObservableCollections,我需要在一个ListView控件来显示他们在一起。为此,我创建MergedCollection其中介绍这两个集合为一体的ObservableCollection。这样我可以设置ListView.ItemsSource我的合并收集和收藏品都被列出。添加工作正常,但是当我尝试删除某个项目,显示未处理的异常:
I have two ObservableCollections and I need to show them in one ListView control together. For this purpose I created MergedCollection which presents these two collections as one ObservableCollection. This way I can set the ListView.ItemsSource to my merged collection and both collections are listed. Adding works fine but when I try to Remove an item, unhandled exception is shown:
An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: Added item does not appear at given index '2'.
MergedCollection的代码如下:
The code of MergedCollection follows:
public class MergedCollection : IEnumerable, INotifyCollectionChanged
{
ObservableCollection<NetworkNode> nodes;
ObservableCollection<NodeConnection> connections;
public MergedCollection(ObservableCollection<NetworkNode> nodes, ObservableCollection<NodeConnection> connections)
{
this.nodes = nodes;
this.connections = connections;
this.nodes.CollectionChanged += new NotifyCollectionChangedEventHandler(NetworkNodes_CollectionChanged);
this.connections.CollectionChanged += new NotifyCollectionChangedEventHandler(Connections_CollectionChanged);
}
void NetworkNodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
CollectionChanged(this, e);
}
void Connections_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
CollectionChanged(this, e);
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
for (int i = 0; i < connections.Count; i++)
{
yield return connections[i];
}
for (int i = 0; i < nodes.Count; i++)
{
yield return nodes[i];
}
}
#endregion
#region INotifyCollectionChanged Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
}
问候
Regards
推荐答案
是否有你不能用任何理由的 CompositeCollection ?
Is there any reason you can't use CompositeCollection?
异常被抛出的原因是因为你没有翻译的指标里面的收藏外。你只是传递完全相同的事件参数外事件(在 MergedCollection
),这就是为什么WPF找不到该项目所在的索引告诉它找到它们。
The reason the exception is being thrown is because you're not translating the indexes of the inner collections to the outer. You're just passing the exact same event args to the outer event (on MergedCollection
), which is why WPF doesn't find the items where the index is telling it to find them.
这篇关于合并的ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!