WrapPanel In WPF

WrapPanel in WPF

A WrapPanel control is used to arrange child controls vertically or horizontally. This article demonstrates how to create and use a WrapPanel control in WPF using XAML and C#.

Creating a WrapPanel

The WrapPanel element represents a Silverlight WrapPanel control in XAML.

  1. <WrapPanel ></WrapPanel >  

The orientation property is used to wrap child items horizontally or vertically.

The code snippet in Listing 1 creates a WrapPanel control and sets its orientation to horizontal. The output looks like Figure 5 where all child controls are wrapped horizontally.

  1. <Grid x:Name="LayoutRoot" Background="White">  
  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>  

Listing 1

The output looks like Figure 5.

WrapPanel Output
Figure 1

Now if you change orientation to vertical like Listing 2, the output looks like Figure 2.

  1. <WrapPanel Orientation="Vertical">  

Listing 2

As you can see in Figure 6, the new controls are aligned vertically.

WrapPanel In WPF Output
Figure 2

WrapPanel.xaml is:

  1. <Window x:Class="HelloWPF.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Wrap Panel" Height="400" Width="300" AllowsTransparency="False" WindowStyle="ThreeDBorderWindow" Background="BlanchedAlmond" FlowDirection="LeftToRight" HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">  
  2.     <Grid x:Name="LayoutRoot" Background="White">  
  3.         <WrapPanel Orientation="Vertical">  
  4.             <Ellipse Width="100" Height="100" Fill="Red" />  
  5.             <Ellipse Width="80" Height="80" Fill="Orange" />  
  6.             <Ellipse Width="60" Height="60" Fill="Yellow" />  
  7.             <Ellipse Width="40" Height="40" Fill="Green" />  
  8.             <Ellipse Width="20" Height="20" Fill="Blue" />  
  9.             <Rectangle Width="100" Height="100" Fill="Cyan" Cursor="None" FlowDirection="RightToLeft"></Rectangle>  
  10.             <Rectangle Width="80" Height="80" Fill="DarkGoldenrod"></Rectangle>  
  11.             <Rectangle Width="60" Height="60" Fill="Chartreuse"></Rectangle>  
  12.             <Rectangle Width="40" Height="40" Fill="Coral"></Rectangle>  
  13.             <Rectangle Width="20" Height="20" Fill="DarkGoldenrod"></Rectangle>  
  14.         </WrapPanel>  
  15.     </Grid>  
  16. </Window>  
Output is:
WrapPanel In WPF Output
Figure 3

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