WPF 入门教程StackPanel介绍

StackPanel是非常相似的WrapPanel,但至少有一个重要的区别:StackPanel的不换行的内容。相反,它将内容向一个方向拉伸,允许您将一项一项一项地堆叠在一起。让我们首先尝试一个非常简单的示例,就像我们对 WrapPanel 所做的一样:

<Window x:Class="WpfTutorialSamples.Panels.StackPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="StackPanel" Height="160" Width="300">
	<StackPanel>
		<Button>Button 1</Button>
		<Button>Button 2</Button>
		<Button>Button 3</Button>
		<Button>Button 4</Button>
		<Button>Button 5</Button>
		<Button>Button 6</Button>
	</StackPanel>
</Window>

您应该注意到的第一件事是 StackPanel 并不真正关心是否有足够的空间容纳内容。它不会以任何方式包装内容,也不会自动为您提供滚动功能(尽管您可以使用 ScrollViewer 控件 - 后面的章节会详细介绍)。

您可能还会注意到 StackPanel 的默认方向是 Vertical,与 WrapPanel 的默认方向是 Horizo​​ntal 不同。但就像 WrapPanel 一样,可以使用 Orientation 属性轻松更改:

<StackPanel Orientation="Horizontal">

您可能会注意到的另一件事是 StackPanel 默认会拉伸其子控件。在垂直对齐的 StackPanel 上,就像第一个示例中的那样,所有子控件都被水平拉伸。在水平对齐的 StackPanel 上,所有子控件都会垂直拉伸,如上所示。StackPanel 通过将其子控件上的 Horizo​​ntalAlignment 或 VerticalAlignment 属性设置为 Stretch 来实现这一点,但如果您愿意,您可以轻松地覆盖它。看看下一个示例,我们使用与前一个示例相同的标记,但这次我们为所有子控件的 VerticalAlignment 属性赋值:

<Window x:Class="WpfTutorialSamples.Panels.StackPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="StackPanel" Height="160" Width="300">
	<StackPanel Orientation="Horizontal">
		<Button VerticalAlignment="Top">Button 1</Button>
		<Button VerticalAlignment="Center">Button 2</Button>
		<Button VerticalAlignment="Bottom">Button 3</Button>
		<Button VerticalAlignment="Bottom">Button 4</Button>
		<Button VerticalAlignment="Center">Button 5</Button>
		<Button VerticalAlignment="Top">Button 6</Button>
	</StackPanel>
</Window>

我们使用 Top、Center 和 Bottom 值将按钮放置在一个漂亮的图案中,只是为了踢球。对于垂直对齐的 StackPanel 当然也可以这样做,您可以在子控件上使用 Horizo​​ntalAlignment:

<Window x:Class="WpfTutorialSamples.Panels.StackPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="StackPanel" Height="160" Width="300">
	<StackPanel Orientation="Vertical">
		<Button HorizontalAlignment="Left">Button 1</Button>
		<Button HorizontalAlignment="Center">Button 2</Button>
		<Button HorizontalAlignment="Right">Button 3</Button>
		<Button HorizontalAlignment="Right">Button 4</Button>
		<Button HorizontalAlignment="Center">Button 5</Button>
		<Button HorizontalAlignment="Left">Button 6</Button>
	</StackPanel>
</Window>

如您所见,控件仍然从上到下排列,但不是具有相同的宽度,而是每个控件都向左、向右或居中对齐。

推荐一款好用的WPF MVVM框架开源控件库《Newbeecoder.UI》

https://www.zhihu.com/video/1520750149983100928

Demo下载:

编辑于 2022-06-16 12:51