c# - 为什么 ItemsSource 不绑定(bind)到我的自定义 CollectionChanged 事件

标签 c# .net windows-8

这是我遇到过的最奇怪的事情。由于在 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/

相关文章:

c# - 字符串中某个字符出现的次数

c# - 在 C# 中生成地理引用图像

c# - "run an instance in a separate Thread"最简单的方法是什么?

C# .Net 4.0 mscorlib 包含 ReadOnlyDictionary?

c# - C# 中对象的名义存储分配

internet-explorer - 什么是网站的简单/最小 browserconfig.xml

c# - 如何以单独的形式将文本框文本提交到匹配列中的listView

c++ - Windows 8、C++ 和 Metro GUI 示例?

javascript - GridLayout ListView 的渲染非常慢 - WinJS

c# - 合并(合并?)并简化/减少 GeoJson 的 DbGeometry 记录