获取ICollectionView的Count属性

问题描述 投票:4回答:1

我有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方法。

c# wpf mvvm collections observablecollection
1个回答
8
投票

试试这样;

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

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

© www.soinside.com 2019 - 2024. All rights reserved.