Merged ObservableCollection

Zef*_*efo 12 c# collections wpf merge observablecollection

我有两个ObservableCollections,我需要在一个ListView控件中一起显示它们.为此,我创建了MergedCollection,它将这两个集合显示为一个ObservableCollection.这样我就可以将ListView.ItemsSource设置为我的合并集合,并列出两个集合.添加工作正常,但当我尝试删除项目时,显示未处理的异常:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: Added item does not appear at given index '2'.
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

问候

Ken*_*art 24

你有什么理由不能使用CompositeCollection吗?

抛出异常的原因是因为您没有将内部集合的索引转换为外部集合.您只是将完全相同的事件args传递给外部事件(on MergedCollection),这就是为什么WPF找不到索引告诉它找到它们的项目.

你这样使用CompositeCollection:

<ListBox>
  <ListBox.Resources>
    <CollectionViewSource x:Key="DogCollection" Source="{Binding Dogs}"/>
    <CollectionViewSource x:Key="CatCollection" Source="{Binding Cats}"/>
  </ListBox.Resources>
  <ListBox.ItemsSource>
    <CompositeCollection>
      <CollectionContainer Collection="{Binding Source={StaticResource DogCollection}}"/>
      <CollectionContainer Collection="{Binding Source={StaticResource CatCollection}}"/>
    </CompositeCollection>
   </ListBox.ItemsSource>
   <!-- ... -->
</ListBox>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此答案.