首页 > 解决方案 > 当表单中没有剩余空间时,对齐下一行​​中的按钮

问题描述

我有一个 WPF 表单,其中一行中有多个按钮。当您调整表单大小时,它应该显示将在下一行中被切断的按钮。我怎样才能做到这一点?

<DockPanel Height="700" Margin="0,0,0,40" VerticalAlignment="Bottom" HorizontalAlignment="Center">

   <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
      <Button Height="150" Width="200" VerticalAlignment="Top" Margin="30">t1</Button>
      <Button Height="150" Width="200" VerticalAlignment="Top" Margin="30">t2</Button>
      <Button Height="150" Width="200" VerticalAlignment="Top" Margin="30">t3</Button>
      <Button Height="150" Width="200" VerticalAlignment="Top" Margin="30">t4</Button>
   </StackPanel>

</DockPanel> 

标签: wpfxaml

解决方案


您可以使用 a WrapPanel,它正是这样做的:

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

此外,您可以为按钮创建隐式样式,因此您可以设置一次属性,它们将自动应用于包装面板范围内的所有按钮。

<WrapPanel DockPanel.Dock="Bottom">
   <WrapPanel.Resources>
      <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
         <Setter Property="Margin" Value="30"/>
         <Setter Property="Height" Value="150"/>
         <Setter Property="Width" Value="200"/>
      </Style>
   </WrapPanel.Resources>
   <Button>t1</Button>
   <Button>t2</Button>
   <Button>t3</Button>
   <Button>t4</Button>
</WrapPanel>

Height设置按钮的另一种方法Width是在环绕面板上设置ItemHeightItemWidth属性,但您必须在此处考虑边距(所有四个边都 +30 下降)。

<WrapPanel DockPanel.Dock="Top" ItemHeight="210" ItemWidth="260">
   <WrapPanel.Resources>
      <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
         <Setter Property="Margin" Value="30"/>
      </Style>
   </WrapPanel.Resources>
   <Button>t1</Button>
   <Button>t2</Button>
   <Button>t3</Button>
   <Button>t4</Button>
</WrapPanel>

推荐阅读