This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Layout Controls - WrapPanel

The ninth part of the Windows Presentation Foundation Fundamentals tutorial continues the description of the WPF layout controls. This instalment considers the WrapPanel, which automatically arranges its child controls into rows or columns.

Automatic Control Sizing

The previous examples included child controls with fixed heights and widths so that you could easily see the wrapping provided by a WrapPanel. In the final example we'll look at what happens when some child controls do not have fixed sizes.

In a horizontal WrapPanel, the controls are organised into rows. If none of the controls in a row have a specified height, each row will automatically take the smallest height possible that allows its content to remain visible. If one or more child controls do have a fixed height, the row's height will match that of the tallest control, including any margin requirements. Once the row's height has been determined, all child controls that have the default vertical alignment will be stretched to fill the row. Controls with a vertical alignment will be positioned accordingly within the available space.

In a vertically-orientated WrapPanel the behaviour is similar but the column widths are controlled by the sizes of their children and child controls may stretch to fill the widths of each column.

This leads to interesting behaviour when the child controls differ in size. We can demonstrate this with the following modified XAML. Here the WrapPanel is horizontal and three of the buttons have unspecified widths. Only the third button has a fixed size.

<WrapPanel Margin="10" Background="Lavender">
    <Button Content="Button 1" Width="100" Margin="3"/>
    <Button Content="Button 2" Width="100" Margin="3"/>
    <Button Content="Button 3" Width="100" Height="50" Margin="3"/>
    <Button Content="Button 4" Width="100" Margin="3"/>

When you run the program you will see the following results. Here the first row contains no buttons with a fixed height. This means that both of the buttons at the top of the panel are sized to their contents. The second row includes button 3, with its larger height. This forces the second row to expand to match the size of the third button. As the fourth button has no specified height or vertical alignment, it too is enlarged to fill the height of the row.

WPF WrapPanel with Automatic Sizing

If you widen the window until the third button jumps into the first row, the layout will be reorganised. Now the larger button is in the first row so this becomes taller and buttons 1 and 2 stretch to fill the row's height. The fourth button shrinks to the size of its content, as does the second row.

WPF WrapPanel with Automatic Sizing

9 April 2013