Drop-dead easy layout management






4.33/5 (13 votes)
Flexible control repositioning and resizing with an easy-to-use layout manager.
Introduction
This article describesLayoutManager
, a
lightweight class that lets you easily reposition and resize controls when the
size of their container changes. Although the .NET framework provides
out-of-the-box support for anchoring (and consequently automated layout
management), we prefer to use a class that is absurdly flexible and something
we understand intuitively. LayoutManager
replaces terminology such as "table layout", "grid-bag layout",
"rubber layout", etc. with four simple adjustments on a control's edge:
- adjust left percentage
- adjust top percentage
- adjust right percentage
- adjust bottom percentage
How to use LayoutManager
You useLayoutManager
by:
- initializing it
- giving it controls to manage
- calling its
alignItems()
method within your container'sSizeChanged
event handler
Load
event
handler.
// Step 1: Initialize the layout manager
m_layoutMgr.init (this);
Controls to be managed by LayoutManager
are added as
instances of LayoutManagerItem
s, each of which refer
to a control and how it should be repositioned and/or resized.
You can add, remove and modify LayoutManagerItem
s
at any time during the execution of your program.
// Step 2: Add controls to the layout manager
m_layoutMgr.Items.Add
(new LayoutManagerItem
(m_editTitle, // the control
0, // don't change L edge
0, // don't change top edge
100, // grow width by 100% of change
66)); // grow height by 66% of change
...
Finally, your form's SizeChanged
event handler
instructs the layout manager to align its items.
private void LayoutManagerDemoFrm_SizeChanged
(object sender, EventArgs e)
{
// Step 3: Instruct the layout manager to align items
m_layoutMgr.alignItems();
}
How it works
LayoutManager
works by saving the container's orginal
size (within init()
), computing the change in the
container's width and height and applying adjustments to each
item under its control according to the item's adjustment rules
(within alignItems()
).
LayoutManagerItem
encapsulates a reference to the
control to be repositioned or resized, and four boolean properties
that describe the adjustment to be performed. LayoutManagerItem
s
are stored in LayoutManager
's Items
property.
Revision history
- 3 Sep 2006
Added ability to control percentage of change in dimensions.
-- Eddie Zhou, Ravi Bhavnani - 1 Jul 2006
Initial version.
-- Ravi Bhavnani