布局控件
常用布局控件
- Grid:网格,根据自定义行和列来设置控件的布局
- StackPanel:栈式面板,包含的元素在竖直或水平方向排成一条直线
- WrapPanel:自动折行面板,包含的元素在排满一行后,自动换行
- DockPanel:泊靠式面板,内部的元素可以选择泊靠方向
- UniformGrid:网格,UniformGrid就是Grid的简化版,每个单元格的大小相同
- Canvas:画布,内部元素根据像素为单位绝对坐标进行定位。
- Border:装饰的控件,此控件用于绘制边框及背景,在Border中只能有一个子控件
这里除了Border控件,其他控件都继承于Panel基类。
Panel基类
所有Panel元素都支持FrameworkElement定义的基本大小调整和定位属性,包括Height、Width、HorizontalAlignment、VerticalAlignment、Margin和LayoutTransform。Panel公开对了解和使用布局至关重要的其他属性。Background属性用于借助Brush填充派生面板元素的边界之间的区域。Children表示组成Panel的子元素集合。InternalChildren表示Children集合的内容以及由数据绑定生成的成员。两者均由父Panel内承载的子元素的UIElementCollection组成。
Panel提供了附加属性,ZIndex。假如一个单行单列的Grid布局控件中有两个Button,正常情况下,这两个Button都会以撑满Grid中,那么到底哪一个Button在上面,哪一个在下面。就看这两个Button的Panel.ZIndex附加属性的值,值越大的在上面,而值较小的那个Button将被上面的Button遮盖,从而在视觉上,用户只能看到一个Button。
<Grid Background="AliceBlue" PreviewMouseUp="Grid_PreviewMouseUp">
<Button Panel.ZIndex="2" Content="按钮1" Width="200" Height="30"/>
<Button Panel.ZIndex="0" Content="按钮2" Width="200" Height="30"/>
</Grid>
Grid(网格)
Grid控件是WPF中所有布局控件中最好用的一个,因为它是自适应屏幕的宽度,最关键的一点是,它在呈现时,其ActuaWidth实际宽度和ActualHeight实际高度会有一个计算值,我们在业务开发中,有时候要根据父控件的实际宽度和高度来计算子控件的呈现位置和大小。
<Window x:Class="WpfApp1.MyGrid"
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:WpfApp1"
mc:Ignorable="d"
Title="MyGrid" Height="450" Width="800">
<!--展示线条-->
<Grid ShowGridLines="True">
<!--三行-->
<Grid.RowDefinitions>
<RowDefinition Height="*" /> <!--Height="100" 固定高度-->
<RowDefinition Height="2*"/> <!--Height="2*" 等比例的高度-->
<RowDefinition Height="2*"/> <!--Height="Auto" 跟随文本的高度-->
</Grid.RowDefinitions>
<!--两列-->
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/> <!--Width="Auto" 跟随文本的宽度-->
</Grid.ColumnDefinitions>
<!--第一行第一列-->
<!--Grid.RowSpan="2" 合并单元格行-->
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2" Text="文本1" Grid.Row="0" Grid.Column="0" FontSize="30"/>
<!--第一行第二列-->
<TextBlock Text="文本2" Grid.Row="0" Grid.Column="1" FontSize="30"/>
<!--<TextBlock Text="文本3" Grid.Row="1" Grid.Column="0" FontSize="30"/>-->
<TextBlock Text="文本4" Grid.Row="1" Grid.Column="1" FontSize="30"/>
<!--Grid.ColumnSpan="2" 合并单元格列-->
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
Grid.ColumnSpan="2"
Text="文本5" Grid.Row="2" Grid.Column="0" FontSize="30"/>
<!--<TextBlock Text="文本6" Grid.Row="2" Grid.Column="1" FontSize="30"/>