当CompositeCollection的当前位置发生变化时,有没有一种获取通知的方式?
我需要让CollectionView监视CompositeCollection,欢迎任何想法。
当CompositeCollection的当前位置发生变化时,有没有一种获取通知的方式?
我需要让CollectionView监视CompositeCollection,欢迎任何想法。
您可以通过监视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"
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;
}
}
}
你不能在复合集合上运行CollectionView,请查看这里