Reputation: 3409
So I have a listview with a hierarchical data template containing signal graph.
<HierarchicalDataTemplate
DataType="{x:Type ViewModels:BusViewModel}"
ItemsSource ="{Binding Path = bits}"
>
<Components:SignalGraph
x:Name="signal_graph"
/>
If I remove an item from itemslist, the signalgraph remains and is still hooked onto the redraw event, so I'm having redraw events for items that are not on screen.
My first instinct was to go and change VirtualizingStackPanel.VirtualizationMode="Standard" so as to be certain that the container wasn't being reused, but that is not enough to stop the redraws.
However, I am merely using the virtualizing tile panel from here: http://blogs.msdn.com/b/dancre/archive/2006/02/16/implementing-a-virtualizingpanel-part-4-the-goods.aspx
and I don't think it implements recycling. It looks to just be using generator's remove and generatenext methods rather than the recycle method. So I'm rather confused as to why the generated objects are not being disposed of correctly. When I look in the cleanupItems method of the panel
private void CleanUpItems(int minDesiredGenerated, int maxDesiredGenerated)
{
UIElementCollection children = this.InternalChildren;
IItemContainerGenerator generator = this.ItemContainerGenerator;
for (int i = children.Count - 1; i >= 0; i--)
{
GeneratorPosition childGeneratorPos = new GeneratorPosition(i, 0);
int itemIndex = generator.IndexFromGeneratorPosition(childGeneratorPos);
if (itemIndex < minDesiredGenerated || itemIndex > maxDesiredGenerated)
{
generator.Remove(childGeneratorPos, 1);
RemoveInternalChildRange(i, 1);
}
}
}
I find that the panel's internal children does get reduced to 1, so I think that WPF is supposed to be taking care of most of this for me. I therefore am of the opinion that I probably need to implement IDisposable or something along these lines to ensure that the control is destroyed and all event handlers are detached.
How do I properly dispose of items when removing it from the observable collection that belongs to the listview's itemssource?
Upvotes: 0
Views: 2287
Reputation: 3409
I just hooked onto the unloaded event and deattached the event handler, and now the code works fine. I am guessing behind the scenes the itemscontrol tries to destroy the object if there are no references to it or something
Upvotes: 0
Reputation: 8791
You are on the right track. Calling generator.Remove does remove the container from generators cache but if you have events or handlers remaining between the item and container the container will not get collected by GC.
Therefore release all the handlers and wpf will take care of removing container from memory, actually GC will remove it. Like you mentioned in first sentence you seem to have some drawing event. If you do not release that event, the container will not get finalized.
So simply release all your custom logic you have in there and you should do fine.
Upvotes: 1