More Layout with Docking
After my recent articles about visual inheritance (Visual Inheritance - How to escape Layout Hell and Visual Inheritance Revisited) I received some mails in which people asked me about docking and windows forms layout in general. One question was about how to resize elements of a layout proportionally when the form is resized, without calculating lots of coordinates.
Imagine you have a form like this:
and you want it to resize like this:
Using docking, this is really easy:
Step 1: Docking
- panel1: Dock left
- label1: Width 1, Dock left
- panel2: Dock top
- label2: Height 1, Dock top
- panel3: Dock fill
(DockPadding.All=8)
Step 2: Handling the form's resize event
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
int dx=this.ClientSize.Width - this.DockPadding.Left - this.DockPadding.Right - label1.Width;
int dy=this.ClientSize.Height - this.DockPadding.Top - this.DockPadding.Bottom - label2.Height;
panel1.Size=new Size(dx/3,panel1.Height);
panel2.Size=new Size(panel2.Width,dy/2);
}
You only need to calculate one width and one height - everything else is taken care of automatically by simply docking the layout elements.