Laying it on the line

In WPF, the layout system is responsible for attaining the sizes of each element to be displayed, positioning them on screen, and then drawing them. As controls can be contained within other controls, the layout system works recursively, with each child control's overall position being determined by the position of its parent panel control.

The layout system first measures each child in each panel in what is known as a measure pass. During this pass, each panel calls the Measure method of each child element and they specify how much space they would ideally like to have; this determines the UIElement.DesiredSize property value. Note that this is not necessarily how much space they will be given.

After the measure pass comes the arrange pass, when each panel calls the Arrange method of each child element. During this pass, the panels generate the bounding boxes of each of their child elements, dependent upon their DesiredSize values. The layout system will adjust these sizes to add any required margins or additional adjustments that may be needed.

It returns a value to the input parameter of the panels' ArrangeOverride method and each panel performs its own specific layout behavior before returning the possibly adjusted value. The layout system performs any remaining required adjustments before returning execution to the panel and completing the layout process.

We need to be careful when developing our applications to ensure that we do not unnecessarily trigger additional passes of the layout system, as this can lead to poor performance. This can occur when adding or removing items in a collection, applying transforms on the elements, or by calling the UIElement.UpdateLayout method, which forces a new layout pass.