WPF教程(三十一)Grid网格跨越

来源:互联网 发布:java用户登录注册代码 编辑:程序博客网 时间:2024/06/05 08:15

Grid默认每一个控件占据一个单元格,但是有些情况下你需要某个控件占据多行或者多列。在这种情况下,可以使用ColumnSpan和RowSpan这两个附加属性来实现。这两个属性默认的值都是1,也就是一个单元格,你可以指定大于1的数字来让控件跨越多行或者多列。

下面的例子使用了ColunmSpan属性:

<span style="font-size:14px;"><Window x:Class="WpfTutorialSamples.Panels.GridColRowSpan"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="GridColRowSpan" Height="110" Width="300">        <Grid>                <Grid.ColumnDefinitions>                                                <ColumnDefinition Width="1*" />                        <ColumnDefinition Width="1*" />                </Grid.ColumnDefinitions>                <Grid.RowDefinitions>                        <RowDefinition Height="*" />                        <RowDefinition Height="*" />                </Grid.RowDefinitions>                <Button>Button 1</Button>                <Button Grid.Column="1">Button 2</Button>                <Button Grid.Row="1" Grid.ColumnSpan="2">Button 3</Button>        </Grid></Window></span>
A Grid with column spanning applied to one of the controls

我们定义了两行两列,分配一样的空间。前两个按钮和正常使用一样,第三个按钮使用了ColumnSpan属性,使得它占据了第二行的两列。

上面的场景比较简单,因此联合几个面板也可以实现这个效果,但是在某些复杂的场景下,上面的功能就非常有用了。下面继续来看一个例子:

<span style="font-size:14px;"><Window x:Class="WpfTutorialSamples.Panels.GridColRowSpanAdvanced"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="GridColRowSpanAdvanced" Height="300" Width="300">    <Grid>                <Grid.ColumnDefinitions>                        <ColumnDefinition Width="*" />                        <ColumnDefinition Width="*" />                        <ColumnDefinition Width="*" />                </Grid.ColumnDefinitions>                <Grid.RowDefinitions>                        <RowDefinition Height="*" />                        <RowDefinition Height="*" />                        <RowDefinition Height="*" />                </Grid.RowDefinitions>                <Button Grid.ColumnSpan="2">Button 1</Button>                <Button Grid.Column="3">Button 2</Button>                <Button Grid.Row="1">Button 3</Button>                <Button Grid.Column="1" Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="2">Button 4</Button>                <Button Grid.Column="0" Grid.Row="2">Button 5</Button>        </Grid></Window></span>

A Grid with both column and row spanning applied to several child controls

三行三列就能产生9个单元格,但是在这个例子中,我们将5个按钮填充到了对应的空间。一个控件可以跨越多行、多列、或者同时跨越多行多列,像按钮4一样。

总之,在Grid里跨越多行或者多列非常容易。在后面的文章中,我们将通过一个更加实用的例子,来演示使用其他Grid技术实现跨越。



0 0