Windows Forms AutoSize usage (.NET bug included)
Although development of Windows Forms stopped two .NET versions ago and was pretty much replaced by WPF, there are still legacy .NET applications around based on Windows Forms. Since mixing WPF and Forms is generally a bad idea, this small article aims to show that dynamic and flexible layouts are still possible and in fact easily achieved in Windows Forms. I will also show you that there are certain hoops that need to be jumped over like .NET bugs.
Consider creating flexible and dynamic dialogs such as message boxes. Form can be designed with a certain layout in mind, but without giving explicit sizes for each control. This way we can design how the elements should be arranged without knowing the exact content that will be put inside. This is available by using powerfull
AutoSize property. Set it to true and also set set the
AutoSizeMode property to
To create flexible layout, we will use the same principle on various containers. For container arrangement, we can use docking behavior. Let’s add two panels, each with auto sizing enabled and let’s dock them to the top. Inside each panel we will add a label which serves as dynamic source of content. This “dynamic” content will be hardcoded in our
Form.Load function since this is a simple demonstration.
Your form in design view may look similar to the following picture. The colors are here just to differentiate panels.
However, when you run this application the resulting dialog will look something like this.
This was clearly not our intention. So how do we fix this? The answer is simpler than you might think. Simply add master
FlowLayoutPanel which will have
Dock value set to
Fill and will also use auto sizing. Then dock the previous two panels inside that panel. Do not forget to change the flow direction to
- Set the margin on the master flow layout and both panels to 0
- Set the padding to 3 for both labels
- Set maximum size to something reasonable (although this should be computed at runtime).
Final result looks something like this (notice that you cannot see pinkish color):
I would also recommend that the panels are replaced with the flow layout panels since they are better suited for dynamic arrangement of content.
Some quick tips for development:
- Use dummy text for labels. Without it, labels will shrink and you will become frustrated very soon.
- Maximum and minimum sizes are your friend.
- Margin and padding are extremely useful. If you have ever done some web coding, you will know how to use it to your advantage.