当窗体中没有剩余空间时,对齐下一行中的按钮



我有一个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> 

您可以使用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>

设置按钮HeightWidth的另一种选择是在包裹面板上设置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>

最新更新