views:

104

answers:

1

I have a menu that used to be a treeview control but now I want to make each item a bit more visual and add some more information to each object in the tree.

My first intention was to make a user control that represents an item and add them to a panel at runtime. Is this a good aproach? There could sometimes be over one hundred items. I know that there is a maximum number of controls you can theoretically hav on a form, but that is not my main concern. My concern is mainly about performance.

Another aproach I was thinking about was to make a listbox and do the extra stuff in the onPaint method. But that seems a bit unstable and a bit too complex to maintain.

Any thoughts?


EDIT:

I've tested the usercontrol-approach by adding 200 usercontrols to the panel att form_Load and it takes a fair amount of time for the actual adding but there doesn't seem to be any performance issues aother than that. Scrolling works fine and I've made each usercontrol collapsable and that functionallity doesn't lag in any way, even when there are about a hundred above and a hundred under it in the panel.

But still ... Am I totally of track here?

+2  A: 

UserControls are very "heavy" animals, as is any instance of System.Windows.Forms.Control, since each one wraps an actual underlying native Win32 Window. Every Window needs to be managed by the OS, hit-tested, sent paint messages, etc.

The traditional solution for this scenario in Windows is to "virtualize" the control. Instead of creating 200 UserControls, maintain an array of 200 "objects" representing each item. Create one "big" control that represents the entire menu, add a ScrollBar to it, and override OnPaint, drawing only the visible items.

This is what the old-school native controls like ListBox and TreeView do.

Now I believe Windows can help you out a bit here, depending on how fancy you need to get. The keyword you're looking for is "owner-drawn". Cribbing from another answer:

Subclass ListBox. In the ctor, set the draw mode to OwnerDrawVariable and override OnDrawItem and OnMeasureItem.

This way, the native controls will handle all the scrolling and math necessary to figure out where you're at in the list and where to start painting.

Nick Farina
That was my main concern regarding the usercontrol, that is was essentially an "App in an app". Your suggested approach seems alot more cost effective. I will give it a shot. Thanks"
Charlie boy