4

I'm working on implementing a user control that changes its size depending on some properties. As I understand winforms layout engine asks each child control for its preferred size when it performs a layout and informs them about the maximum size that they can afford.

This is a description of GetPreferredSize in msdn:

Control.GetPreferredSize(Size proposedSize)

Retrieves the size of a rectangular area into which a control can be fitted.

I'm confused by the following:

You can return a size larger than the constraints indicated in the proposedSize parameter, but proposedSize should decrease as the constraint decreases.

What does it mean? What will happen if I return the size larger than proposed?

Can somebody explain me how does this work?

Community
  • 1
  • 1
username
  • 3,378
  • 5
  • 44
  • 75

2 Answers2

2

What that line means is that you are free to return a larger preferred size than the proposedSize parameter, but that proposedSize should still be affecting your preferred size. For example, your returned size for GetPreferredSize(new Size(100, 0) should be less than the returned size for GetPreferredSize(new Size(200, 0)).

Note that nothing bad happens if you return a larger size; the layout engine will sort everything out for you, possibly by reducing the size available for another control. Ultimately, your preferred size is just a hint for the engine, so that it knows what the relative space demands are for the various UI components it is arranging.

dlev
  • 48,024
  • 5
  • 125
  • 132
1

The Control.GetPreferredSize is called by containers as part of the layout cycle.

It allows the called control to return the size they would like to have if possible. The container does not have to honor this requested size however. For example, when a control has a Dock setting of Top the width would be defined as the width of the containing control regardless of the value returned from the GetPreferredSize method. This method is particularly useful for containers like the flow layout control which will position each child control one after another.

Phil Wright
  • 22,580
  • 14
  • 83
  • 137
  • What about labels? When they have Dock set to DockStyle.Top they do not change their width – username Jun 28 '11 at 09:43
  • I think in general they are defined as AutoSize=False and so they ignore the size you give them and size to what they want regardless. – Phil Wright Jun 28 '11 at 10:48
  • So container honors the size of the child control only in case AutoSize = true, correct? – username Jun 28 '11 at 11:19
  • No, the container tells the control the size it should be but the Label just ignores it and stays how it likes. – Phil Wright Jun 28 '11 at 11:56