如果没有指定RowDefinitions和Column Definitions,网格布局为什么不工作?

时间:2013-06-03 13:38:30

标签: xaml windows-store-apps

<Page
    x:Class="AllControls.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:AllControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">



        <Rectangle Width="100" Height="100" Fill="Red" Grid.Column="0" Grid.Row="0"/>
        <Rectangle Width="100" Height="100" Fill="Orange"  Grid.Column="1"  Grid.Row="0"/>
        <Rectangle Width="100" Height="100" Fill="Yellow"  Grid.Column="0" Grid.Row="1"/>
        <Rectangle Width="100" Height="100" Fill="Green" Grid.Column="1"  Grid.Row="1"/>
        <Rectangle Width="100" Height="100" Fill="Blue" Grid.Column="0" Grid.Row="2"/>
        <Rectangle Width="100" Height="100" Fill="Indigo" Grid.Column="1" Grid.Row="2"/>
        <Rectangle Width="100" Height="100" Fill="Violet" Grid.Column="0" Grid.Row="3"/>
        <Rectangle Width="100" Height="100" Fill="Purple" Grid.Column="1" Grid.Row="3"/>
    </Grid>
</Page>

我在这种情况下为每个元素提供行号和列号矩形。我还为每个人提供了高度和宽度。

我来自HTML背景。

有人可以向我解释一下RowDefinitions和ColumnDefinitions标签是如何工作的吗?

2 个答案:

答案 0 :(得分:2)

您必须指定RowDefinitions和ColumnDefinitions,以便它知道如何调整行和列的大小。否则,它不知道您是否要自动调整大小或star-sizing。而且还需要知道前面需要多少行和列;它不会根据Grid.Row和Grid.Column的值动态添加它们。

我认为你编写的代码看起来很合理,如果你没有指定它会使用默认值会很好,但不幸的是它没有。相反,它构建一个单列的单行网格,并将所有子项堆叠在一起。

我可以想出几种方法来编写一些可以做你想做的XAML。

一种方式:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Rectangle Width="100" Height="100" Fill="Red" Grid.Column="0" Grid.Row="0"/>
    <Rectangle Width="100" Height="100" Fill="Orange"  Grid.Column="1"  Grid.Row="0"/>
    ...
</Grid>

另一种方式:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="100" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="100" />
        <RowDefinition Height="100" />
        <RowDefinition Height="100" />
        <RowDefinition Height="100" />
    </Grid.RowDefinitions>
    <Rectangle Fill="Red" Grid.Column="0" Grid.Row="0"/>
    <Rectangle Fill="Orange"  Grid.Column="1"  Grid.Row="0"/>
    ...
</Grid>

答案 1 :(得分:1)

就像安德鲁先生所指出的那样,你必须使用指定的RowDefinition / ColumnDefinition更多地定义你的布局,以便基本上手动铺设你的东西。如果您正在寻找更加流畅的东西而不需要定义布局结构,那么您应该查看GridView / VariableSizeWrapGrid(我认为更多的是您正在寻找的内容。)

这两个网站都有多个examples,并且很容易习惯。希望这有助于您从HTML过渡到XAML(ps,在我看来是XAML&gt; HTML)

:)

相关问题