I am using a StackPanel to layout several controls vertically (ie, Title, sub titles, listbox, separator, listbox, etc).
The StackPanel is a child of a ScrollViewer to ensure its content is always scrollable.
One of the controls in the StackPanel is a ListBox.
Its ItemsSource is data bound to a huge collection, and a complex DataTemplate is used to realise each item.
Unfortunately, I'm getting really poor performance (high cpu/memory) with it.
I tried
- setting the ListBox's ItemsPanel to a VirtualizingStackPanel, and
- overriding its ControlTemplate to only an ItemsPresenter (remove the ListBox's ScrollViewer).
But there were no difference in performances. I'm guessing the StackPanel gives its internal children infinite height during measure?
When I replaced the ScrollViewer and StackPanel with other panels/layouts (e.g, Grid, DockPanel) and the performance improves significantly, which leads me to believe the bottleneck, as well as solution, is in virtualization.
Is there any way for me to improve the cpu/memory performance of this view?

[Update 1]
Original Sample project: http://s000.tinyupload.com/index.php?file_id=29810707815310047536
[Update 2]
I tried restyling/templating TreeView/TreeViewItems to come up with the following example. It still takes a long time to start/same,high memory usage. But once loaded, scrolling feels a lot more responsive than the original sample.
Wonder if there's any other way to further improve the start up time/memory usage?
Restyled TreeView project: http://s000.tinyupload.com/index.php?file_id=00117351345725628185
[Update 2]
pushpraj's solution works like a charm
- Original:
- Startup: 35s,
- Memory: 393MB
- Scrolling: Slow
- TreeView:
- Startup: 18s,
- Memory 377MB,
- Scrolling: Fast
- pushpraj's solution:
- Startup: <1s,
- Memory: 20MB,
- Scrolling: Fast
you may perhaps limit the maximum size of the huge list box and enable
Virtualizationeg
this will enable the ListBox to load a few items only and will enable a scrollbar on listbox to scroll to rest of the items if needed.
at the same time setting
VirtualizationModetoRecyclingwill help you to reuse the complex data templates thus eliminating the need of re creating them again for every item.EDIT
here is a solution based on your sample, I have used
CompositeCollectionwithVirtualizationto achieve the desired.xaml
code
since we can not create data template for string so I changed the string collection to
Permissioncollection. I hope in your real project it would be something similar.give this a try and see if this is close to what you need.
note: you may safely ignore if there is any designer warning on
Collection="{Binding DataContext, Source={x:Reference listbox}}"