当CompositeCollection的当前位置发生变化时,有没有办法得到通知?
我需要通过CollectionView监控CompositeCollection,任何想法都很受欢迎。
答案 0 :(得分:6)
您可以通过监控CollectionView的ICollectionView.CurrentChanged
事件来检测当前项目的更改时间。以下代码适用于我:
CompositeCollection cc = new CompositeCollection();
cc.Add(new CollectionContainer { Collection = new string[] { "Oh No!", "Fie" } });
cc.Add(new CollectionContainer { Collection = new string[] { "Zounds", "Ods Bodikins" } });
CollectionViewSource cvs = new CollectionViewSource { Source = cc };
// Subscribing to CurrentChanged on the ICollectionView
cvs.View.CurrentChanged += (o, e) => MessageBox.Show("current changed");
lb.ItemsSource = cvs.View; // lb is a ListBox with IsSynchronizedWithCurrentItem="True"
当我更改ListBox中的选择时,将显示消息框。
关于过滤,排序和分组,根据Aron的回答,这些在CompositeCollection的视图上不可用。但是,对于以下记录,您可以检测做支持这些功能的视图的更改:
ObservableCollection<GroupDescription>
,因此请在GroupDescriptions属性上连接CollectionChanged事件处理程序。答案 1 :(得分:0)
您无法在复合集合上运行集合视图,请设置here
答案 2 :(得分:0)
我遇到了同样的问题:我需要对CompositeCollection进行排序。我写了下面的类来解决这个问题,至少对于同一类型的ObservableCollections来说。
我们的想法是将复合集合维护为普通的可观察集合,并在底层集合发生更改时对其进行更新。然后生成的集合(AllNodes)可以在用户界面中使用,它支持CollectionView就好了。
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
namespace Util {
public class ObservableCollectionCollector<T> {
private class ReplacableObservableCollection : ObservableCollection<T> {
public void Replace(int idx, T v) {
SetItem(idx, v);
}
}
private readonly ReplacableObservableCollection allNodes;
private readonly ObservableCollection<T>[] colls;
private readonly int[] lens;
public ObservableCollectionCollector(params ObservableCollection<T>[] colls) {
this.colls = colls;
allNodes = new ReplacableObservableCollection();
foreach (var l in colls) {
foreach (var e in l)
allNodes.Add(e);
l.CollectionChanged += HandleCollectionChanged;
}
lens = colls.Select(c => c.Count).ToArray();
}
public ReadOnlyObservableCollection<T> AllNodes {
get { return new ReadOnlyObservableCollection<T>(allNodes); }
}
private void HandleCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
int i0 = 0;
int ci = 0;
foreach (var l in colls) {
if (l == sender)
break;
i0 += l.Count;
++ci;
}
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
for (int i = 0; i < e.NewItems.Count; ++i)
allNodes.Insert(i0 + e.NewStartingIndex + i, (T)e.NewItems[i]);
break;
case NotifyCollectionChangedAction.Move:
for (int i = 0; i < e.OldItems.Count; ++i)
allNodes.Move(i0 + e.OldStartingIndex + i, i0 + e.NewStartingIndex + i);
break;
case NotifyCollectionChangedAction.Remove:
for (int i = 0; i < e.OldItems.Count; ++i)
allNodes.RemoveAt(i0 + e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
for (int i = 0; i < e.NewItems.Count; ++i)
allNodes.Replace(i0 + e.OldStartingIndex + i, (T)e.NewItems[i]);
break;
case NotifyCollectionChangedAction.Reset:
for (int i = 0; i < lens[ci]; ++i)
allNodes.RemoveAt(i0);
break;
}
lens[ci] = ((ObservableCollection<T>)sender).Count;
}
}
}