Bamba news

WinUI 3|XAMLで使えるレイアウトパネルの基本と配置方法

XAMLコードエディターでレイアウトパネルを用いた配置方法を解説します。

Tags:#WinUI3

主なレイアウトパネルと使い方

  • Grid

※上部の黒い四角はデバッグ時のツールボックスです

grid.png
<Grid>
    <!--行方向を設定-->
    <Grid.RowDefinitions>
        <!--必要に応じて自動調整-->
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    
    <!--列方向を設定-->
    <Grid.ColumnDefinitions>
        <!--px単位で設定-->
        <ColumnDefinition Width="100"/>
        <!--*の2倍の幅に設定-->
        <ColumnDefinition Width="2*"/>
        <!--残りを自動分配-->
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <TextBox 
        Text="0,0"
        BorderBrush="Gray" 
        BorderThickness="2"
        Grid.Row="0"
        Grid.Column="0"/>

    <TextBox 
        Text="0,1"
        BorderBrush="Gray" 
        BorderThickness="2"
        Grid.Row="0"
        Grid.Column="1"/>

    <TextBox
        Text="0,2"
        BorderBrush="Gray"
        BorderThickness="2"
        Grid.Row="0"
        Grid.Column="2"/>

</Grid>

  • StackPanel →要素を一列に並べる(横:horizontal、縦:vertical)
stackPanel.png
<StackPanel Orientation="Vertical">
    <TextBlock Text="ボタン一覧"/>
    <Button Content="ボタン1"/>
    <Button Content="ボタン2"/>
    <Button Content="ボタン3"/>
</StackPanel>

  • Canvas →絶対座標で位置を指定
canvas.png
<Canvas>
    <Button Content="ボタン" Canvas.Left="100" Canvas.Top="200"/>
</Canvas>

  • RelativePanel →ほかの要素との相対的な位置関係で設定する
relativepanel.png
<RelativePanel>
    <Button x:Name="button1"
            Content="基準"
            RelativePanel.AlignHorizontalCenterWithPanel="True"
            RelativePanel.AlignVerticalCenterWithPanel="True"/>
    <Button Content="右側"
            RelativePanel.RightOf="button1"
            RelativePanel.AlignVerticalCenterWith="button1"/>
    <Button Content="左側"
            RelativePanel.LeftOf="button1"
            RelativePanel.AlignVerticalCenterWith="button1"/>
</RelativePanel>

補足
英語ではありますが、公式リファレンス(https://learn.microsoft.com/en-us/windows/apps/design/layout/layout-panels)を見ると使えるプロパティがわかりやすいと思います。

関連する記事

Bamba news