获取ICollectionView的Count属性

Lub*_*Suk 4 c# collections wpf observablecollection mvvm

我有ICollectionView

private ICollectionView _snapshotList;

    public ICollectionView SnapshotList {
        get { return _snapshotList; }
    }
Run Code Online (Sandbox Code Playgroud)

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

_snapshotList = CollectionViewSource.GetDefaultView(this.snapshotListModel.SnapshotItems);
        _snapshotList.Filter = ErrorMsgFilter;
        _snapshotList.CollectionChanged += OnCollectionChanged;
Run Code Online (Sandbox Code Playgroud)

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

        void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
        this.ItemCount = _snapshotList.Count();
    }
Run Code Online (Sandbox Code Playgroud)

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

luc*_*cky 9

试试这样;

_snapshotList.Cast<object>().Count();
Run Code Online (Sandbox Code Playgroud)

ICollectionView实现,IEnumarable但它没有实现IEnumerable<TSource>List<TSource>,HashSet<TSource>等等.因此,ICollectionView没有泛型类型,我们必须将其IEnumerable<object>强制转换为启用Count()方法.