13

我有两个 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'.

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
}

问候

4

2 回答 2

27

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

引发异常的原因是您没有将内部集合的索引转换为外部集合。您只是将完全相同的事件参数传递给外部事件 (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>

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

于 2009-04-22T12:54:10.417 回答
4

您必须偏移通知事件的索引。

假设您从索引 2 处的第一个集合中删除了一个项目。集合更改事件在索引 2 处触发。

如果您从索引 2 处的第二个集合中删除一个项目,则使用相同的索引 (2) 触发该事件,但该项目实际上是在第一个集合中的所有项目之后枚举的。

于 2009-04-22T13:14:13.770 回答