概述
初学WPF,本文主要用来记录几种常见的WPF布局容器,包括Grid,DockPanel,WrapPanel,StackPanel,UniformGrid ;
1.Grid
可以通过定义Grid的RowDifinitions和ColumnDifinitions,来定义行列数,并可以自由设定行列的大小(固定值,按比例,Auto),同时子元素可以通过定义Row和Column来决定放在哪个位置。
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Content="Button" Background="Red"/>
<Button Grid.Row="1" Grid.Column="1" Content="Button" Background="Blue" />
<Button Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Content="Button" Background="Green" />
<Button Grid.Row="3" Content="Button" Grid.ColumnSpan="2" Background="SkyBlue"/>
</Grid>
2.DockPanel
带有停靠属性的容器,子元素用4个值来控制停靠位置:Left、Top、Right、Bottom,最后的子元素将加入一个DockPanel并填满所有剩余的空间,除非DockPanel的LastChildFill属性为false
<DockPanel LastChildFill="False">
<Button Content="Button左" DockPanel.Dock="Left" Background="Red"/>
<Button Content="Button右" DockPanel.Dock="Right" Background="Yellow"/>
<Button Content="Button上" DockPanel.Dock="Top" Background="blue"/>
<Button Content="Button下" DockPanel.Dock="Bottom" Background="Green"/>
</DockPanel>
3.WarpPanel
WrapPanel布局面板将各个控件按照一定方向罗列,当长度或高度不够时自动调整进行换行换列。Orientation="Horizontal"时各控件从左至右罗列,当面板长度不够时,子控件就会自动换行,继续按照从左至右的顺序排列。Orientation=" Vertical"时各控件从上至下罗列,当面板高度不够时,子控件就会自动换列,继续按照从上至下的顺序排列。
<WrapPanel Orientation="Horizontal">
<Button Content="Button1" Width="150"/>
<Button Content="Button2" Width="200"/>
<Button Content="Button3" Width="150"/>
<Button Content="Button4" Width="200"/>
<Button Content="Button5" Width="150"/>
<Button Content="Button6" Width="200"/>
<Button Content="Button7" Width="150"/>
</WrapPanel>
4.StackPanel
StackPanel将控件按照行或列来顺序排列,不会换行。通过设置面板的Orientation属性设置了两种排列方式:横排(Horizontal默认的)和竖排(Vertical),默认为竖排(Vertical)。
<StackPanel Orientation="Horizontal">
<Button Content="Button1"/>
<Button Content="Button2"/>
<Button Content="Button3"/>
</StackPanel>
<StackPanel Orientation="Vertical">
<Button Content="Button4"/>
<Button Content="Button5"/>
<Button Content="Button6"/>
</StackPanel>
5.UniformGrid
UniformGrid 就是Grid的简化版,每个单元格的大小相同,不需要定义行列集合。每个单元格始终具有相同的大小,每个单元格只能容纳一个控件。若不设置Rows Colums,则按照定义在其内部的元素个数,自动创建行列,并通常保持相同的行列数。若只设置Rows则固定行数,自动扩展列数。若只设置Colums则固定列数,自动扩展行数。UniformGrid 中没有Row和Column附加属性,也没有空白单元格。
<UniformGrid>
<Button Content="Button1"/>
<Button Content="Button2"/>
<Button Content="Button3"/>
<Button Content="Button4"/>
<Button Content="Button5"/>
<Button Content="Button6"/>
<Button Content="Button7"/>
</UniformGrid>