我有兩個ObservableCollections,我需要在一個ListView控件中一起顯示它們。爲此我創建了MergedCollection,它將這兩個集合呈現爲一個ObservableCollection。這樣我可以將ListView.ItemsSource設置爲我的合併集合,並且列出了這兩個集合。添加工作正常,但是當我嘗試刪除某個項目,則會顯示未處理的異常:合併ObservableCollection
An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: Added item does not appear at given index '2'.
MergedCollection的代碼如下:
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
}
問候
CompositeCollection不實現INotifyCollectionChanged。 – 2009-04-22 13:00:20
@Josh:如果你關注鏈接,你會發現它確實如此。 – 2009-04-22 13:03:03