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

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技術實現跨越。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章