WPF DockPanel 对空间进行分区

74

使用 DockPanel 元素创建简单的用户界面(UI)框架。 DockPanel 将可用空间分配给其子元素。

  • DockPanel.Dock="Top|Right|Bottom|Left"设置元素位置

  • LastChildFill="False" 设置最后一个子元素不填充剩余的未分配空间

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

        <!--DockPanel 用于修饰部分空间元素排布-->
        <!--DockPanel DockPanel.Dock="Top|Right|Bottom|Left"设置元素位置-->
        <DockPanel Grid.Row="0" Grid.Column="0" Background="Bisque">
            <Button Width="auto" Height="30" Content="按钮1" DockPanel.Dock="Top"/>
            <Button Width="100" Height="auto" Content="按钮4" DockPanel.Dock="Left"/>
            <Button Width="100" Height="auto" Content="按钮2" DockPanel.Dock="Right"/>
            <Button Content="按钮3" DockPanel.Dock="Bottom"/>
        </DockPanel>
        <!--默认情况下,DockPanel 元素的最后一个子元素填充剩余的未分配空间。 如果不希望此行为,请设置 LastChildFill="False"。-->
        <DockPanel Grid.Row="0" Grid.Column="1" Background="BurlyWood" LastChildFill="False">
            <Button Width="auto" Height="30" Content="按钮1" DockPanel.Dock="Top"/>
            <Button Width="100" Height="auto" Content="按钮4" DockPanel.Dock="Left"/>
            <Button Width="100" Height="auto" Content="按钮2" DockPanel.Dock="Right"/>
            <Button Content="按钮3" DockPanel.Dock="Bottom"/>
        </DockPanel>
    </Grid>
</UserControl>

默认情况下,DockPanel 元素的最后一个子元素填充剩余的未分配空间。 如果不希望此行为,请设置 LastChildFill="False"