How to get Items count from CollectionViewSource?

后端 未结 6 677
鱼传尺愫
鱼传尺愫 2021-01-17 09:19

I am using CollectionViewSource to filter the records displayed in a ListBox. The xaml follows.

   

        
相关标签:
6条回答
  • 2021-01-17 09:25

    You could also do _viewSource.View.Cast<object>().Count() for the filtered list and _viewSource.View.SourceCollection.Cast<object>().Count() for the original.

    0 讨论(0)
  • 2021-01-17 09:35

    I think the better solution is, as usual, Linq!

    _viewSource.View.Cast<[your_type]>().Count();
    

    ...or...

    _viewSource.View.Cast<object>().Count();
    

    ...if you don't know the items' type at runtime!

    0 讨论(0)
  • 2021-01-17 09:40

    The source collection and collectionview both implements IEnumerable so you can always iterate over them and count how many are in them. But I would only recommend doing this if you have no access to the actual collection you used as source.

    private void SetSummary() 
    {
        int initialCount = 0;
        foreach(var item in _viewSource.View.SourceCollection)
        {
            initialCount++;
        }
    
        int filteredCount = 0;
        foreach (var item in _viewSource.View)
        {
            filteredCount++;
        }
    }
    
    0 讨论(0)
  • 2021-01-17 09:43
    var count = DataGrid.ItemsSource.OfType<object>().Count();
    
    0 讨论(0)
  • 2021-01-17 09:45
    public static int Count(this ICollectionView view)
        {
            var index = 0;
            foreach (var unused in view)
            {
                index++;
            }
            return index;
        }
    
    0 讨论(0)
  • 2021-01-17 09:49

    If you're doing MVVM, you could have your VM create a collection view rather than one being created on your behalf by the CollectionViewSource. Then, you have control over what type of CVS is created, so you can create a ListCollectionViewSource, which has a Count property. It really depends on the properties of the data you're filtering.

    0 讨论(0)
提交回复
热议问题