Search code examples
wpfbindingicollectionviewcollectionview

Binding a combobox to a CollectionView shows filtered out elements. Why?


Wpf binding is funny for those who know it well and it is nightmare for newbie. If I bind a combobox to the commented out CollectionView the control shows all the elements, including those excluded by the filter. If I bind the same combobox to a ICollectionView it displays only the filtered elements and it is Ok.

 //public CollectionView MyCapitoliList { get; private set; }
 public ICollectionView MyCapitoliList { get; private set; }

Here is the code I use to create the CollectionView and ICollectionView

MyCapitoliList = CollectionViewSource.GetDefaultView(listaCapitoli);
//MyCapitoliList = new CollectionView(listaCapitoli);


MyCapitoliList.Filter = new Predicate<object>(isCapitoloMaster);

I checked the CollectionView printing all its elements from C# code and it contains only the filtered elements, so the CollectionView is Ok. Why do I get all the unfiltered elements if I bind it to a combobox ?

Thanks Filippo


Solution

  • MSDN says about CollectionView class...

    You should not create objects of this class in your code. To create a collection view for a collection that only implements IEnumerable, create a CollectionViewSource object, add your collection to the Source property, and get the collection view from the View property.

    It further adds ...

    In WPF applications, all collections have an associated default collection view. Rather than working with the collection directly, the binding engine always accesses the collection through the associated view. To get the default view, use the CollectionViewSource.GetDefaultView method.