WPF StackPanel 水平或垂直堆叠子元素

137

StackPanel 元素用于水平或垂直堆叠子元素

  • Orientation="Vertical" 排列方式从上往下排列(默认排列方式)

  • Orientation="Horizontal" 设置从左往右水平排列

2025-03-20-todwdhfw.png

<UserControl x:Class="WpfApp1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>
        
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <!--StackPanel 用于修饰部分空间元素排布-->
        <!--StackPanel 默认排列方式从上往下排列-->
        <!--StackPanel 不能自动换行自动换列-->
        <StackPanel Grid.Row="0" Grid.Column="0" Background="WhiteSmoke">
            <Button Width="100" Height="20" Content="按钮1"/>
            <Button Width="100" Height="20" Content="按钮2"/>
            <Button Width="100" Height="20" Content="按钮3"/>
            <Button Width="100" Height="20" Content="按钮4"/>
            <Button Width="100" Height="20" Content="按钮5"/>
            <Button Width="100" Height="20" Content="按钮6"/>
            <Button Width="100" Height="20" Content="按钮7"/>
            <Button Width="100" Height="20" Content="按钮8"/>
            <Button Width="100" Height="20" Content="按钮9"/>
        </StackPanel>
        <!--StackPanel 属性Orientation=Horizontal设置水平排列-->
        <StackPanel Grid.Row="0" Grid.Column="1" Background="AliceBlue" Orientation="Vertical">
            <Button Width="100" Height="20" Content="按钮1"/>
            <Button Width="100" Height="20" Content="按钮2"/>
            <Button Width="100" Height="20" Content="按钮3"/>
            <Button Width="100" Height="20" Content="按钮4"/>
            <Button Width="100" Height="20" Content="按钮5"/>
            <Button Width="100" Height="20" Content="按钮6"/>
            <Button Width="100" Height="20" Content="按钮7"/>
            <Button Width="100" Height="20" Content="按钮8"/>
            <Button Width="100" Height="20" Content="按钮9"/>
        </StackPanel>
    </Grid>
</UserControl>