星空雅梦

WPF教程二:布局之StackPanel面板

 

应用程序界面设计中,合理的元素布局至关重要,它可以方便用户使用,并将信息清晰合理地展现给用户。WPF提供了一套功能强大的工具-面板(Panel),来控制用户界面的布局。你可以使用这些面板控件来排布元素。如果内置布局控件不能满足需要的话,还可以创建自定义的布局元素。

面板(Panel)
WPF用于布局的面板主要有6个,StackPanel(栈面板)、WrapPanel(环绕面板)。DockPanel(停靠面板)、Canvas(画布)、Grid(网格面板)和UniformGrid(均布网格)。

StackPanel:栈面板

栈面板,可以将元素排列成一行或者一列,其特点是:每个元素各占一行或者一列,Orientation属性指定排列方式:Vertical(垂直)【默认】、Horizontal(水平),默认情况下,水平排列时,每个元素都与面板一样高;垂直排列时,每个元素都与面板一样宽。如果包含的元素超过了面板空间,它只会截断多出的内容。 元素的Margin属性用于使元素之间产生一定得间隔,当元素空间大于其内容的空间时,剩余空间将由HorizontalAlignment和 VerticalAlignment属性来决定如何分配。

1、垂直方向排列

界面运行效果:

使用XAML代码实现:

复制代码
 1 <Window x:Class="WpfDemo.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         Title="StackPanel面板" Height="237" Width="525" WindowStartupLocation="CenterScreen">
 5     <StackPanel x:Name="stackpanel" Margin="0" Orientation="Vertical">
 6         <Button Content="第一个"></Button>
 7         <Button Content="第二个"></Button>
 8         <Button Content="第三个"></Button>
 9         <Button Content="第四个"></Button>
10     </StackPanel>
11 </Window>
复制代码

2、水平方向排列

界面运行效果:

使用XAML代码实现:

复制代码
 1 <Window x:Class="WpfDemo.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         Title="StackPanel面板" Height="237" Width="525" WindowStartupLocation="CenterScreen">
 5     <StackPanel x:Name="stackpanel" Margin="0" Orientation="Horizontal">
 6         <Button Content="第一个"></Button>
 7         <Button Content="第二个"></Button>
 8         <Button Content="第三个"></Button>
 9         <Button Content="第四个"></Button>
10     </StackPanel>
11 </Window>
复制代码

注: 当把StackPanel的FlowDirection属性设置为RightToLeft,Orientation属性设置为Horizontal,StackPanel将从右向左排列元素。

 
分类: WPF
原文地址:https://www.cnblogs.com/LiZhongZhongY/p/10871969.html