获取ICollectionView的Count属性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取ICollectionView的Count属性相关的知识,希望对你有一定的参考价值。

我有ICollectionView

private ICollectionView _snapshotList;

    public ICollectionView SnapshotList {
        get { return _snapshotList; }
    }

我在ViewModel构造函数中进行设置,其中this.smapshotListModel.SnapshotItems返回ObservableCollection

_snapshotList = CollectionViewSource.GetDefaultView(this.snapshotListModel.SnapshotItems);
        _snapshotList.Filter = ErrorMsgFilter;
        _snapshotList.CollectionChanged += OnCollectionChanged;

后来在collectionChanged事件我试图获取此集合中的项目数,

        void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
        this.ItemCount = _snapshotList.Count();
    }

但它的抛出错误,就是没有定义Count方法。

答案

试试这样;

_snapshotList.Cast<object>().Count();

ICollectionView实施IEnumarable,但它没有像IEnumerable<TSource>List<TSource>等那样实现HashSet<TSource>。所以,ICollectionView没有通用类型,我们必须将其投射到IEnumerable<object>一次以启用Count()方法。

以上是关于获取ICollectionView的Count属性的主要内容,如果未能解决你的问题,请参考以下文章