Upper (reasonable) limit to number of user control instances

前端 未结 1 1810
刺人心
刺人心 2020-12-19 21:03

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 firs

相关标签:
1条回答
  • 2020-12-19 21:25

    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.

    0 讨论(0)
提交回复
热议问题