这是我遇到过的最奇怪的事情。由于在 Windows 8 MS 中从 CollectionViewSource 中删除了过滤和排序,我必须构建自己的,名为 CollectionView<T>
。 CollectionView
具有类型为 IObservableCollection<T>
的 View 属性,我制作的一个自定义界面只是为了保持事物的抽象性。它的定义非常简单
public interface IObservableCollection<T> : IReadOnlyList<T>, INotifyCollectionChanged
{
}
然后,我有一个实现此接口(interface)的内部类:
internal class FilteredSortedCollection<T> : IObservableCollection<T>
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public void RaiseCollectionChanged(NotifyCollectionChangedEventArgs args)
{
var copy = CollectionChanged;
if (copy != null)
copy(this, args);
}
public Func<IEnumerator<T>> RequestEnumerator { get; set; }
public Func<int> RequestCount { get; set; }
public Func<int, T> RequestItem { get; set; }
public IEnumerator<T> GetEnumerator()
{
return RequestEnumerator();
}
public int Count { get { return RequestCount(); } }
public T this[int index] { get { return RequestItem(index); } }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
事情一直到这里为止。 CollectionView 正确过滤和排序,并且 View 按预期工作。除非我将它绑定(bind)到 ListView.ItemsSource 属性,它的行为就好像它没有实现 INotifyCollectionChanged
。没有人监听 CollectionChanged 事件(使用调试器检查),并且UI 不会随着添加的新元素而更新。但是,如果我添加一些项目,然后设置 ItemsSource 属性,UI 就会更新。就像一个普通的、不可观察的列表一样。
有人知道这里会发生什么吗?我尝试删除 IObservableCollection
接口(interface),所以FilteredSortedCollection
刚刚实现IReadOnlyList<T>
和INotifyCollectionChanged
直接,但没有成功。
最佳答案
您的集合需要实现 IList。我刚刚遇到了同样的问题,我实现了 IList,它在我的 Windows Phone 应用程序中运行得很好,但是当我尝试使用 Windows 8 应用程序的 View 模型时,它不支持更改的事件。
我将 IList 的实现添加到我的类中,现在一切都按预期工作
关于c# - 为什么 ItemsSource 不绑定(bind)到我的自定义 CollectionChanged 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165356/