'MeasureOverride and ArrangeOverride. What is really AvailableSize/DesiredSize?

I've been stuck for two days trying to understand the layout principles of WPF.

I have read a bunch of articles and explored the wpf source code.

I know that measure/measureoverride method accepts a availablesize and then sets the DesiredSize property. This makes sense. It recursively calls to the children and ask them to set their respective desired size.

There are two things (at least) I don't understand. Let us consider a WrapPanel.

  • Looking at the WPF source code, the MeasureOverride() method accepts an availablesize and then passes this to all the children. It then returns the largest width and largest height of the resulting desiredsize properties in the children. Shouldn't it divide the available space between the children? I would think that it would iterate over the children and then measure the first, then subtract the resulting desiredsize from the total availablesize so that the next child had less space to occupy. As I read the WPF, WrapPanel.MeasureOverride does not appear to set a desiredsize that it would need to fit all the children. It just gives the DesiredSize that any ONE of the children will fit in to.
  • Due to the nature of the wrappanel, I would expect that for a vertically oriented stackpanel a restriction in height would result in a wider DesiredSize (to fit more columns). Since a restriction in height affects the desired size of a wrap panel, doesn't this logic then belong in the MeasureOverride method? Why is the stacking then only reflected in the ArrangeOverride method?

I think I have some fundamental misunderstanding about the mechanics of these two method.

Can anybody give me a verbal description of DesiredSize and/or AvailableSize that makes this implementation make sense?



Solution 1:[1]

@grx70 answer is great and amazingly detailed. However, there is much more to know about the WPF layouting system and I wrote a whole article about it on CodeProject: Deep Dive into WPF Layouting and Rendering

Here is an overview how Properties and overwriting of MeasureOverride(), ArrangeOverride() and OnRender() work together to produce and use DesiredSize and RenderSize (which is by the way the exactly same value like ActualHeight and ActuelWidth).

enter image description here

For a detailed description see the article.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Huber