我有两个可观察集合,我需要在一个ListView控件中一起显示它们。为此,我创建了mergedCollection,它将这两个集合表示为一个可观察集合。这样,我可以将ListVIEW.ItEsStand设置为合并的集合,并列出两个集合。添加可以正常工作,但当我尝试删除某个项时,将显示未处理的异常:
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吗?
引发异常的原因是您没有将内部集合的索引转换为外部集合。您只是将完全相同的事件参数传递给外部事件(onMergedCollection
),这就是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/