5. Grid
Grid可能是面板类型中最复杂的。Grid可以包含多行和多个列。您为每行定义一个高度,为每列定义一个宽度,以像素的绝对数量、可用空间的百分比或自动方式,其中行或列将根据内容自动调整其大小。当其他面板不适合使用时, 使用Grid,例如,当您需要多个列并且经常与其他面板组合时。
在最基本的形式中,Grid将简单地接受您放入其中的所有控件,将它们拉伸以使用最大可用空间并将他们堆叠:
<Window x:Class="WpfTutorialSamples.Panels.Grid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Grid" Height="300" Width="300">
<Grid>
<Button>Button 1</Button>
<Button>Button 2</Button>
</Grid>
</Window>
正如你所看到的,最后一个控件覆盖了位置,在这种情况下意味着你甚至看不到第一个按钮。不过,对于大多数情况来说,这并不是非常有用,所以让我们试着划分空间,这就是网格所能做到的。
我们通过使用ColumnDefinitions和RowDefinitions定义来实现这一点
<Window x:Class="WpfTutorialSamples.Panels.Grid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Grid" Height="300" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button>Button 1</Button>
<Button Grid.Column="1">Button 2</Button>
</Grid>
</Window>
在这个示例中,我们简单地将可用空间划分为两列,它们将使用“星形宽度”(这将在后面解释)来平均共享空间。
让我们输入更多的列,甚至是一些行,用于一个真正的表格布局:
<Window x:Class="WpfTutorialSamples.Panels.TabularGrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TabularGrid" Height="300" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />