WPF WrapPanel 自动换行换列

155

WrapPanel 元素将子元素按从左到右的顺序定位,将内容分到其包含框边缘的下一行。

  • 能自动换行自动换列

  • Orientation="Horizontal" 设置水平靠左排列(默认排列方式)

  • Orientation="Vertical" 设置垂直靠左排列

2025-03-20-xggksqmd.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>

        <!--WrapPanel 用于修饰部分空间元素排布-->
        <!--WrapPanel 默认排列方式水平排列-->
        <!--WrapPanel 能自动换行自动换列-->
        <WrapPanel Grid.Row="0" Grid.Column="0" Background="Aqua">
            <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"/>
        </WrapPanel>
        <!--WrapPanel 属性Orientation=Horizontal设置水平排列-->
        <WrapPanel Grid.Row="0" Grid.Column="1" Background="AntiqueWhite" 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"/>
        </WrapPanel>
    </Grid>
</UserControl>