Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace the default CollectionView of an enumerable collection?

When binding an enumerable to an ItemsSource or similar, the binding uses the enumerable's default view, which I know you can get using the following code...

var defaultView = CollectionViewSource.GetDefaultView(someCollection);

This has worked great for us, allowing us to, for instance, add sorting right to the default view of various collections.

However, we have a specialized Collection class which requires a specialized ListCollectionView subclass to work properly. That said, how can we change its default view so that is returned when someone binds directly to the collection?

For a work-around, we created a new property called MainView which holds our custom ListCollectionView, then we bind things like ItemsSource to that, but that means consumers of our collection have to be explicitly told not to bind directly to the collection but rather to the MainView property or they'll get the default view. Considering the standard is just to bind to the collection directly, that's a potential issue we're trying to avoid.

So again, how can I specify my own ListCollectionView subclass as the default view for our custom collection?

like image 645
Mark A. Donohoe Avatar asked Feb 16 '23 04:02

Mark A. Donohoe


1 Answers

On your collection, implement the interface ICollectionViewFactory. Here is an example:

public class MyCollection : ObservableCollection<MyItem>, ICollectionViewFactory
{
    public ICollectionView CreateView()
    {
        return new MyListCollectionView(this);
    }
}
like image 153
JimSt24 Avatar answered Apr 09 '23 22:04

JimSt24