Using XAML WrapPanel in WPF

A WrapPanel is similar to a StackPanel but it does not just stack all child elements in one row. It wraps the elements in new lines if space is inadequate. The orientation can be set to Horizontal or Vertical.

Creating a WrapPanel

The WrapPanel element represents a WrapPanel control in XAML.
The Orientation property is used to wrap child items horizontally or vertically.

When we use the horizontal orientation, child content forms horizontal rows first and if necessary forms vertical stacks of rows.

When we use a vertical orientation, child content is first positioned in a vertical column.

The following code snippet sets the Orientation of a WrapPanel. We can set the Height and Width of WrapPanel manually. The code also sets the Orientation to Horizontal.

  1. <WrapPanel Orientation=”Horizontal”>  
  2.    Children  
  3. </WrapPanel>  
The output looks as in Figure 1 where all the child controls are wrapped horizontally.

Adding WrapPanel Child Element

The WrapPanel control contains the Ellipse and sets the Width, Height and Fill color in it.
  1. <Grid x:Name="layout" Background="BurlyWood">  
  2.    <WrapPanel Orientation="Horizontal">  
  3.       <Ellipse Width="100" Height="100" Fill="Red" />  
  4.       <Ellipse Width="80" Height="80" Fill="Orange" />  
  5.       <Ellipse Width="60" Height="60" Fill="Yellow" />  
  6.       <Ellipse Width="40" Height="40" Fill="Green" />  
  7.       <Ellipse Width="20" Height="20" Fill="Blue" />  
  8.    </WrapPanel> 
  9. </Grid> 
The output looks as in Figure 1.

                     main window
                                                         Figure 1.

Now if you change the orientation to Vertical as in the following code, the output will change like in Figure 2.

The following code snippet will create a WrapPanel and sets its orientation to vertical, all child controls will be wrapped vertically.
  1. <Grid x:Name="layout" Background="BurlyWood">  
  2.    <WrapPanel Orientation="Vertical">  
  3.       <Ellipse Width="100" Height="100" Fill="Red" />  
  4.       <Ellipse Width="80" Height="80" Fill="Orange" />  
  5.       <Ellipse Width="60" Height="60" Fill="Yellow" />  
  6.       <Ellipse Width="40" Height="40" Fill="Green" />  
  7.       <Ellipse Width="20" Height="20" Fill="Blue" />  
  8.    </WrapPanel>  
  9. </Grid>  
The output looks as in Figure 2.

                                 output look like
                                         Figure 2

Summary

In this article, I discussed how to create a WrapPanel control in WPF and C#.

 

Up Next
    Ebook Download
    View all
    Learn
    View all