wpfobservablecollectioncollectionviewsourcecompositecollection

How to handle a CompositeCollection with CollectionView features?


Is there a way to get notified when CompositeCollection's current location changes?

I need to have the CompositeCollection monitored by a CollectionView, any ideas are welcommed.


Solution

  • You can detect when the current item has changed by monitoring the ICollectionView.CurrentChanged event of your CollectionView. The following code works for me:

    CompositeCollection cc = new CompositeCollection();
    cc.Add(new CollectionContainer { Collection = new string[] { "Oh No!", "Fie" } });
    cc.Add(new CollectionContainer { Collection = new string[] { "Zounds", "Ods Bodikins" } });
    CollectionViewSource cvs = new CollectionViewSource { Source = cc };
    
    // Subscribing to CurrentChanged on the ICollectionView
    cvs.View.CurrentChanged += (o, e) => MessageBox.Show("current changed");
    
    lb.ItemsSource = cvs.View;  // lb is a ListBox with IsSynchronizedWithCurrentItem="True"
    

    When I change the selection in the ListBox, the message box displays.

    Regarding filtering, sorting and grouping, as per Aron's answer these are not available on a view over a CompositeCollection. But for the record here are the ways you can detect changes for views that do support these features: