使用Grid布局控件的时候,一些知识点如下:
我们可以通过定义Grid的ColumnDifinitions和RowDifinitions来实现对于表格的定义,然后根据Grid.Column和Grid.Row的对象来制定位置的方式实现布局。
比如上面XAML文件中,
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="5" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
<RowDefinition Height="35"/>
</Grid.RowDefinitions>
|
就定义了一个三行三列的表格。
ColumnDefinition和RowDefinition分别只需要定义Width和Height
如果我们希望列的宽度或者行的高度是根据内部元素来决定的,我们可以定义为Auto,如果我们希望某列或者某行的宽度或者告诉是整体的其他部分,则可以定义成*,如果我们希望其中一项的长度是另外一项的5倍,则可以一个定义成*,一个定义成5*。
我们看ColumnDefinition或者RowDefinition的Width或者Height属性的时候,我们可以看到这个属性不是int或者double类型,而是GridLength类型。
下面一个简单的Grid定义来演示上面定义长度的几种写法:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Column="0" Grid.Row="0" Background="RosyBrown" ></Label>
<Label Grid.Column="1" Grid.Row="0" Background="SkyBlue" >1234567890</Label>
<Label Grid.Column="2" Grid.Row="0" Background="Red" ></Label>
<Label Grid.Column="0" Grid.Row="1" Background="SpringGreen" ></Label>
<Label Grid.Column="1" Grid.Row="1" Background="RoyalBlue" >abc</Label>
<Label Grid.Column="2" Grid.Row="1" Background="Violet" ></Label>
</Grid>
</Window>
|
这个XAML文件的效果图如下:
 |
| 图2 |
此外,我们还可以使用Grid.ColumnSpan、Grid.RowSpan来实现一块布局跨多个表格项的情况。
小结
我个人觉得,把一个窗体或者页面用表格拆分,然后我们在每个表格项中增加我们规划好的控件,这种布局方案在没有比较好的美术细胞下,比较容易做出一个至少不难看的页面布局。
基于以上的考虑,我觉得我们技术人员开发一些WPF窗体或者页面的时候,Grid控件应该是我们最常用到的。也应该是最应该掌握的控件。 |