此示例演示如何创建 StackPanel。
示例
StackPanel 允许您按指定的方向堆积元素。 通过使用在 StackPanel 上定义的属性,内容既可以纵向流出(默认设置),也可以横向流出。
下面的示例使用 StackPanel 纵向堆积了五个 TextBlock 控件,每个控件都有不同的 Border 和 Background。 没有指定的 Width 的子元素将会拉伸以填充父窗口;但是,具有指定的 Width 的子元素将在窗口内集中。
StackPanel 的默认堆积方向为垂直方向。 若要控制 StackPanel 中的内容流,请使用 Orientation 属性。 通过使用 HorizontalAlignment 属性可以控制水平对齐。
<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="StackPanel Sample">
<StackPanel>
<Border Background="SkyBlue" BorderBrush="Black" BorderThickness="1">
<TextBlock Foreground="Black" FontSize="12">Stacked Item #1</TextBlock>
</Border>
<Border Width="400" Background="CadetBlue" BorderBrush="Black" BorderThickness="1">
<TextBlock Foreground="Black" FontSize="14">Stacked Item #2</TextBlock>
</Border>
<Border Background="LightGoldenRodYellow" BorderBrush="Black" BorderThickness="1">
<TextBlock Foreground="Black" FontSize="16">Stacked Item #3</TextBlock>
</Border>
<Border Width="200" Background="PaleGreen" BorderBrush="Black" BorderThickness="1">
<TextBlock Foreground="Black" FontSize="18">Stacked Item #4</TextBlock>
</Border>
<Border Background="White" BorderBrush="Black" BorderThickness="1">
<TextBlock Foreground="Black" FontSize="20">Stacked Item #5</TextBlock>
</Border>
</StackPanel>
</Page>