特点:
1)可以定义任意数量的行和列
2)行的高度和列的宽度可以使用绝对值、相对比例或自动调整的方式,可设置最大值和最小值
3)内部元素可以设置自己所在的行、列,还可以设置跨越几行、几列
4)可以设置内部元素的对齐方向
Grid类具有ColumnDefinitions和RowDefinitions两个属性,它们分别是ColumnDefinition和RowDefinition的集合,表示Grid定义了多少列、多少行,下面这段代码定义了一个3行4列的表格
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="*" />
- <RowDefinition Height="20" />
- <RowDefinition Height="*" />
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="*" />
- <ColumnDefinition Width="30" />
- <ColumnDefinition Width="*" />
- <ColumnDefinition Width="*" />
- </Grid.ColumnDefinitions>
- </Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="20" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="30" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
</Grid>
对于Grid 的行高和列宽,可以设置3类值:
1)绝对值:double数值加单位后缀,默认为像素
2)比例值:double数值后加*
3)自动值:字符串Auto
设置内部控件的起始行用Grid.Row属性,起始列用Grid.Column属性,跨越行使用Grid.RowSpan属性,跨越列使用Grid.ColumnSpan属性
上面代码结果如下
如果希望列宽可以拖动,Grip布局本身是不支持的,需要用Grid布局加上GridSplitter来实现,GridSplitter会改变Grid初始的行高、列宽,代码如下
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="25"></RowDefinition>
- <RowDefinition></RowDefinition>
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="150"></ColumnDefinition>
- <ColumnDefinition Width="Auto"></ColumnDefinition>
- <ColumnDefinition></ColumnDefinition>
- </Grid.ColumnDefinitions>
- <TextBox Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" BorderBrush="Black" />
- <TextBox Grid.Row="1" Grid.Column="0" BorderBrush="Black" />
- <GridSplitter Grid.Row="1" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Center" Width="5" Background="Gray" ShowsPreview="True"></GridSplitter>
- <TextBox Grid.Row="1" Grid.Column="2" BorderBrush="Black" />
- </Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" BorderBrush="Black" />
<TextBox Grid.Row="1" Grid.Column="0" BorderBrush="Black" />
<GridSplitter Grid.Row="1" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Center" Width="5" Background="Gray" ShowsPreview="True"></GridSplitter>
<TextBox Grid.Row="1" Grid.Column="2" BorderBrush="Black" />
</Grid>