I'm wondering what the best practices are for working with CollectionViews in WPF in particular the use of the CollectionViewSource.GetDefaultView() method. Has anyone run into any problems with using GetDefaultView? We're concerned that it may be causing some memory leaks.
Is it generally a better practice to create ListCollectionViews manually rather than rely on GetDefaultView()?
How does WPF manage these views? Do they get GC'd when the collection does? I've seen some articles saying that you need to detach CollectionViews from their source collection otherwise you'll have a memory leak.
Thanks for you help!
Bea states that using CollectionViewSource.GetDefaultView()
is her favorite way for accessing the view of a given collection. In addition I have personally never ran into any issues making use of the CollectionViewSource.GetDefaultView()
however it is certainly possible in a given scenario.
You have to understand that every collection has a default view and that when you bind a given property to a given collection WPF automatically wraps the collection with a view and binds to the view; not the collection.
Since this is part of the WPF framework you then have to assume that with every collection having a view associated with it that it would then be disposed of when the collection is disposed of. If there is a reference to the collection via a bindable property there is then an associated view referencing the collection whether you make a call to CollectionViewSource.GetDefaultView()
or not so you would still be in the same predicament.
Empirical evidence exists that until the collection is out of scope the associated views will not be GC'ed; however keep in mind that this was dealing with a collection with implements INotifyCollectionChanged
.
Based on your circumstance a 1:1 relationship between the collection and associated view may exist and therefore the coupling may provide no hindrance whatsoever. In this scenario the view being GC'ed once the collection has gone out of scope is not an issue.
It boils down to treading with caution and making certain that you know what is happening under the covers for the more complex situations so that you can take the appropriate measures.