2009-04-22 19 views
12

我有兩個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 
} 

問候

回答

21

是否有任何理由,你不能使用CompositeCollection

拋出異常的原因是因爲你沒有將內部集合的索引轉換爲外部索引。您只是將完全相同的事件參數傳遞給外部事件(在MergedCollection上),這就是爲什麼WPF找不到索引要求它找到它們的項目。

+0

CompositeCollection不實現INotifyCollectionChanged。 – 2009-04-22 13:00:20

+1

@Josh:如果你關注鏈接,你會發現它確實如此。 – 2009-04-22 13:03:03

4

您必須抵消通知事件的索引。

說你從第一個集合索引2.刪除項目集合改變事件與指數2

解僱如果從第二收集索引2中刪除項目,該事件與解僱相同的索引(2),但該項目實際上是在第一個集合中的所有項目之後枚舉的。

相關問題