c# - 合并的 ObservableCollection

标签 c# wpf collections 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'.

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

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

有关详细信息,请参阅 this answer .

关于c# - 合并的 ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/777048/

相关文章:

c# - 对具有空值的列表进行排序

c# - DateTime.ParseExact 抛出 System.FormatException

c# - 函数运行时用于显示图片的线程

wpf - ItemsControl 中的绑定(bind)不起作用

wpf - FlowDocument 中的波浪下划线

c# - 在 UWP Windows 10 C# 中创建带边框的圆形按钮

java - 根据值拆分值列表

java - 使用java流从另一个对象列表更新对象列表

java - 为什么 Java 中没有 SortedList?

c# - C#中如何替换两个字符之间的文本