What is the purpose of the Control.GetPreferredSize method?

I am working on the implementation of a user control that changes its size depending on some properties. Since I understand that the winforms layout engine requests each child control for its preferred size when it runs the layout and tells them the maximum size they can afford.

This is the description of GetPreferredSize in msdn:

Control.GetPreferredSize(Size proposedSize) 

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

I am confused by the following:

You can return a size that exceeds the limits specified in the Suggested Size parameter, but the Suggested size should decrease as the limit decreases.

What does it mean? What happens if I return a size that is larger than suggested?

Can someone explain to me how this works?

+4
source share
2 answers

What this string means is that you can return a more preferred size than the proposedSize parameter, but proposedSize should still affect your preferred size. For example, the return size for GetPreferredSize(new Size(100, 0) should be less than the return size for GetPreferredSize(new Size(200, 0)) .

Note that nothing bad happens if you return a larger size; the layout engine sorts everything for you, possibly reducing the size available for another control. Ultimately, your preferred size is just a hint to the engine, so that it knows what relative space is required for the various user interface components it organizes.

+2
source

Control.GetPreferredSize is called by containers as part of the build loop.

It allows the called control to return the size that they would like to have, if possible. However, the container must not comply with this requested size. For example, when a control has a Dock parameter for the upper width, it will be defined as the width of the containing control, regardless of the value returned from the GetPreferredSize method. This method is especially useful for containers, such as controlling the layout of the stream, which will place each child control one by one.

+1
source

All Articles