C#WPFの道#28!WrapPanelの書き方と使い方をわかりやすく解説!

当サイトではアフィリエイト広告を利用しています。

WPF

WrapPanelとは?

WrapPanelはコントロールを置くためのパネルで,縦向きか横向きで順番にコントロールを整列して配置してくれます。コントロールを並べていく際に,コントロールがエリアに入りきらなくなったら,折り返しながらコントロールを並べるのが特徴です。

WrapPanelの書き方

WrapPanelは,コントロールを配置していく方向と,一つのコントロールに割り当てる縦と横の幅を指定します。

Orientation

コントロールを縦に並べるときはVertical,横方向に並べていく場合はHorizontalを指定します。

コントロール1つ分の縦幅をItemHeight,横幅をItemWidthで指定します。

横に並べる例

<WrapPanel Orientation="Horizontal"
           ItemHeight="80"
           ItemWidth="80">
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
</WrapPanel>

縦に並べる例

<WrapPanel Orientation="Vertical"
           ItemHeight="80"
           ItemWidth="80">
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
    <Button Content="AAA" FontSize="20"/>
</WrapPanel>

違いはOrientationのみです。

サンプルコード全体

<Window x:Class="WPF028.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF028"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <WrapPanel Orientation="Horizontal"
                   ItemHeight="80"
                   ItemWidth="80">
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
        </WrapPanel>

        <WrapPanel Grid.Column = "1"
                   Orientation="Vertical"
                   ItemHeight="80"
                   ItemWidth="80">
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
            <Button Content="AAA" FontSize="20"/>
        </WrapPanel>
    </Grid>
</Window>