I'm trying to figure out how come WPF doesn't go crazy when I set a window to resize to its content and then set its content to take all the available space... Any idea?
It's not that difficult: if the window is set to stretch to match its content, then it doesn't have a static size, so it assumes default dimensions. Going down the visual tree, the control wants to stretch to fill the window -- it doesn't force any dimensions, but instead accepts whatever size the window has (the default one).
My guess is that elements always have a size (default one if none specified above them in the hierarchy) and the mention whether that size is fixed or negotiable.
I'm only guessing here, but it's just to prove that the situation is not as bad as it seems. With a good update strategy in place, the elements can adjust in relation to each other in a sane manner.
There are two passes in the layout system - measure and arrange.
First in the measure pass each child is given a proposed available size, and this propagates down the tree. This sets each child's DesiredSize
property.
In the next, arrange pass, the DesiredSize
is taken into account, but the parent has the final word on how much actual available size it will give to a child, and the parent places each child accordingly, informing it of the actual size it gets, and so on down the tree.
Also, consider several imaginable corner cases:
- The child demands
double.Infinity
desired size: explicitly not allowed, raises an exception - The child sets its
HorizontalAlignment
to "Stretch": the parent doesn't offer infinite actual size - Window set to
SizeToConent
, child set to "Stretch
", no other constraint set:- Window first offers infinite measure size
- Child demands the size measured by its children (text width, margins, etc) - not infinite size
- Arrange: window sets its size to a system-defined minimum or as desired by child, whichever is greater (can't be infinite)
- The child stretches to fit the size determined in previous step