5.4 UI布局(Layout)
5.4.1 布局元素
Grid(网格), StackPanel(栈式面板), Canvas(画布), WrapPannel(自动折行面板)
5.4.2 Grid
1. 定义Grid的行与列
Grid类具有ColumnDefinitions和RowDefinitions两个属性,它们分别是ColumnDefinition和RowDefinition的集合,表示Grid定义了多少列,多少行。
比例值是在double类型后面加一个星号("*")。解析器会把所有比例值的数值加起来作为分母,把每个比例值的数值作为分子,再用这个分值乘以未被占用空间的像素数,得到的结果就是分配给这个比例值的最终像素数。
比例值最大的特点是当UI整体尺寸改变后,它会保持固有的比例。
行高和列宽的默认形式就是比例值,所以如果没有显式指定行高或列宽时,默认值就是1*,1*又可以简写为*。
如果你使用自动值(字符串“Auto”)为行高或列宽赋值,那么行高或列宽的实际值将由行列内控件的高度和宽度决定,通俗点讲就是控件会把行列“撑”到合适的高度和宽度。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30px"/> <!--30像素-->
<RowDefinition Height="30"/> <!--30像素-->
<RowDefinition Height="0.5in"/> <!--0.5英寸-->
<RowDefinition Height="1cm"/> <!--1厘米-->
<RowDefinition Height="30pt"/> <!--30点-->
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
</Grid>
2. 使用Grid进行布局
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="120"/>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="4" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25px"/>
<RowDefinition Height="4"/>
<RowDefinition Height="*"/>
<RowDefinition Height="4"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<TextBlock Text="请选择您的部门并留言: " Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" />
<ComboBox Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="4" />
<TextBox Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="5" />
<Button Content="提交" Width="80" Grid.Row="4" Grid.Column="1" HorizontalAlignment="Right"/>
<Button Content="清除" Width="80" Grid.Row="4" Grid.Column="3" />
</Grid>