A Winforms Layout Puzzle
Here’s a strange piece of behaviour – a puzzle (with solution) for you.
Imagine that you’re working with Win.Forms, constructing a resizable layout using a TableLayoutForm as the host.
At Design time, your form looks like this (click to enlarge):
But, at run time it looks like this (click to enlarge):
Notice how the controls are offset down from their proper location.
Each label is configured as follows:
* Anchors: Left (Left align, vertically centered)
* Autosize: true
Each control is configured as follows:
* Anchors: Left | Right (Stretch across cell, vertically centered)
* Maximum Size: (240,0)
Why is this happening? Any ideas?
[Solution below]
Note that the top edge of each control is vertically centred within its’ cell – this is your clue.
Turns out that the TableLayoutPanel pays attention to the MaximumSize property of the controls – with the maximum size of these controls set to (240,0), the panel assumes that all the controls will be zero height and conveniently centred them vertically in their cells.
It doesn't, as I originally expected, treat the controls as having a Maximum Width and *no restriction on height*.
There are a number of possible fixes …
* With the rows of the TableLayoutPanel set to AutoSize, we could set the Anchors of the controls to Left|Top|Right (Stretch across the top of the cell)
* We could remove the MaximumSize property entirely by setting it to (0,0)
* We could set the height of the MaximumSize property to the actual height of the control
I chose the later.
An interesting example of how different features interact in unexpected ways.