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将从右向左排列元素。

posted @   .NET开发菜鸟  阅读(31812)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示