I am using CollectionViewSource to filter the records displayed in a ListBox. The xaml follows.
You could also do _viewSource.View.Cast<object>().Count()
for the filtered list and _viewSource.View.SourceCollection.Cast<object>().Count()
for the original.
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!
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++;
}
}
var count = DataGrid.ItemsSource.OfType<object>().Count();
public static int Count(this ICollectionView view)
{
var index = 0;
foreach (var unused in view)
{
index++;
}
return index;
}
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.