How to get real count of a CollectionView, when Filter is in use?

Houman picture Houman · Nov 21, 2011 · Viewed 10.9k times · Source

When I have a <Label Content="{Binding ItemCount}"/> on my View to bind to a property on the ViewModel.

On the viewmodel I have the property defined as

public int ItemCount
{
    get { RowViewModelsCollectionView.Count; }
}

I am clearly asking for count on the CollectionView, where I am expecting to get the count of only visible items. Unfortunately I get the count of the entire rows, even the ones not showing on the view due the filter.

Update:

in Ctor:

RowViewModelsCollectionView= new ListCollectionView(rowViewModels) {Filter = Contains};


private bool Contains(object obj)
        {
            RowViewModel rowViewModel = obj as RowViewModel;

            if (rowViewModel != null && Books.ContainsKey(rowViewModel.Book))
            {
                RaisePropertyChanged("ItemCount"); // Trying out to raise it without joy
                return true;
            }

            return false;
        }

How should I fix this?

Answer

WPF-it picture WPF-it · Nov 21, 2011

@punker76, is correct in saying that binding should be done to the collection view's Count property directly...

Reason is that CollectionView has implemented INotifyPropertyChanged and notifies property changes for its Count property whenever commit, filtering, grouping, sorting takes place on it...

So assuming that you have RowViewModelsCollectionView as a public / internal property of your view model,

  <Label Content="{Binding RowViewModelsCollectionView.Count}"/> 

.... should work just fine...