WPF布局——布局面板StackPanel
WPF——StackPanel布局控件
StackPanel(堆式面板),将子元素按照声明的先后顺序堆在一起。设置Orientation
属性值确定以水平或垂直方向堆放。
在StackPanel
中,根据子元素的最大尺寸来确定最佳尺寸。
StackPanel实例——堆式面板嵌套
此例设计要求:现在使用堆式面板来实现,在最外层是边框环绕,内部一个StackPanel中再嵌套两个StackPanel,子元素Button。
依旧是在解决方案WpfApp3新建项目:命名项目名字NestingStackPanel。
效果图:
实现代码:
<Window x:Class="NestingStackPanel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:NestingStackPanel"
mc:Ignorable="d"
Title="MainWindow" Height="310" Width="460">
<!-- 设置边界厚度、水平对齐方式、垂直对齐方式 -->
<Border BorderBrush="Black" BorderThickness="1"
HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Height="262" Width="435">
<StackPanel Margin="2" Background="YellowGreen" Orientation="Vertical" >
<Button Content="One " Margin="1" Height="40"/>
<Button Content="Two " Margin="1" Height="40"/>
<Button Content="Three " Margin="1" Height="40"/>
<Button Content="Four " Margin="1" Height="40"/>
<Button Content="Five " Margin="1" Height="40"/>
</StackPanel>
<StackPanel Margin="2" Background="GreenYellow" Orientation="Horizontal" Height="40">
<Button Content="One " Margin="3" Width="80"/>
<Button Content="Two " Margin="3" Width="80"/>
<Button Content="Three " Margin="3" Width="80"/>
<Button Content="Four " Margin="3" Width="80"/>
<Button Content="Five " Margin="3" Width="80"/>
</StackPanel>
</StackPanel>
</Border>
</Window>
StackPanel会根据方向使用无限宽度和高度来测量子控件,当有其他布局同时出现时,会影响布局的整体风格。本例中,通过最外层的Border对StackPanel进行约束。
StackPanel实例——用户搜索页面
StackPanel适合局部页面布局,用它做一个简单的用户搜索页面。
设计要求:使用堆式面板来实现搜索页面,尽可能使用不同的控件作为子元素。项目名称为SearchStackPanel
页面效果如下:
XAML代码如下:
<Window x:Class="SearchStackPanel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SearchStackPanel"
mc:Ignorable="d"
Title="MainWindow" Height="220" Width="360">
<StackPanel Background="AliceBlue">
<TextBlock Margin="4">Look for:</TextBlock>
<ComboBox Margin="4"></ComboBox>
<TextBlock Margin="4">Filtered by:</TextBlock>
<ComboBox Margin="4"></ComboBox>
<Button Margin="4,5">Search</Button>
<CheckBox Margin="4">Search in titles only</CheckBox>
<CheckBox Margin="4">Search in Keyword</CheckBox>
</StackPanel>
</Window>
其中使用了两个TextBlock
、两个ComboBox
、两个CheckBox
和一个Button
构成的页面,设置Margin
属性让页面保持更清爽。
上一篇:WPF编程基础入门 ——— 第三章 布局(三)布局面板DockPanel.
下一篇:WPF编程基础入门 ——— 第三章 布局(五)布局面板WrapPanel.
WPF编程基础入门 ——— 目录导航.