繁体   English   中英

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

[英]Why doesn't ItemsSource bind to my custom CollectionChanged event

这是我经历过的最奇怪的事情。 在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 ,但没有成功。

您的集合需要实现IList。 我刚遇到了在我的Windows Phone应用程序中实现IList的问题,但是当我尝试将View模型用于Windows 8应用程序时,它并没有兑现更改的事件。

我在类中添加了IList的实现,现在一切正常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM