为什么ItemsSource不绑定到我的自定义CollectionChanged事件

时间:2012-08-28 18:33:33

标签: c# .net windows-8

这是我遇到过的最奇怪的事情。由于在Windows 8 MS中从CollectionViewSource中删除了过滤和排序,我必须构建自己的,称为CollectionView<T>CollectionView有一个类型为IObservableCollection<T>的View属性,这是我为了保持抽象而制作的自定义界面。它的定义非常简单

public interface IObservableCollection<T> : IReadOnlyList<T>, INotifyCollectionChanged
{
}

然后,我有我的内部类来实现这个接口:

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按预期工作。除非我将它绑定到ListView.ItemsSource属性,否则它就像没有实现INotifyCollectionChanged 一样。没有人收听CollectionChanged事件(使用调试器检查)和 UI不会更新添加新元素。但是,如果我添加一些项目然后设置ItemsSource属性,则UI会更新。就像它是一个正常的,不可观察的列表一样。

有人知道这里会发生什么吗?我已尝试删除IObservableCollection界面,因此FilteredSortedCollection直接实施了IReadOnlyList<T>INotifyCollectionChanged,但它没有效果。

1 个答案:

答案 0 :(得分:1)

您的收藏需要实施IList。我刚刚遇到了同样的问题,我已经实现了IList,它在我的Windows Phone应用程序中运行得很好,但是当我尝试使用Windows 8应用程序的视图模型时,它并不尊重已更改的事件。

我在我的课程中添加了IList的实现,现在一切都按预期工作了

相关问题