WrapPanel in WPF


WrapPanel in WPF

A WrapPanel control is used to arrange child controls to arrange 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.

 

< 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.

 

<Grid x:Name="LayoutRoot" Background="White" >

    <WrapPanel Orientation="Horizontal">

            <Ellipse Width="100" Height="100" Fill="Red" />

            <Ellipse Width="80" Height="80" Fill="Orange" />

            <Ellipse Width="60" Height="60" Fill="Yellow" />

            <Ellipse Width="40" Height="40" Fill="Green" />

            <Ellipse Width="20" Height="20" Fill="Blue" />         

    </WrapPanel>

</Grid>

Listing 1

The output looks like Figure 5.

Figure 1

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

<WrapPanel Orientation="Vertical">

 

 Listing 2

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

Figure 2

WrapPanel.xaml is :

<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">

    <Grid x:Name="LayoutRoot" Background="White" >

        <WrapPanel Orientation="Vertical">

            <Ellipse Width="100" Height="100" Fill="Red" />

            <Ellipse Width="80" Height="80" Fill="Orange" />

            <Ellipse Width="60" Height="60" Fill="Yellow" />

            <Ellipse Width="40" Height="40" Fill="Green" />

            <Ellipse Width="20" Height="20" Fill="Blue" />

            <Rectangle Width="100"  Height="100" Fill="Cyan" Cursor="None" FlowDirection="RightToLeft"></Rectangle>

            <Rectangle Width="80" Height="80" Fill="DarkGoldenrod"></Rectangle>

            <Rectangle Width="60" Height="60" Fill="Chartreuse"></Rectangle>

            <Rectangle Width="40" Height="40" Fill="Coral"></Rectangle>

            <Rectangle Width="20" Height="20" Fill="DarkGoldenrod"></Rectangle>

       

        </WrapPanel>

    </Grid>

</Window>

Output is :

Figure 3

Summary

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

 

Up Next
    Ebook Download
    View all
    Learn
    View all