自动行和列调整

时间:2017-04-18 00:22:34

标签: wpf xaml

WPF:

有没有办法让网格的行(或列)的宽度和高度完全适合其内容的尺寸?

编辑:

  

[Grid]中的[Grid]

<Grid>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="textBlock1" Background="#FF00AAE7" Foreground="White" Text="1" Height="30" FontSize="20" FontWeight="Bold" TextAlignment="Center"/>
        <TextBlock x:Name="textBlock2" Background="#FFF04937" Foreground="White" Text="2" Height="30" Grid.Row="1" FontSize="20" FontWeight="Bold" TextAlignment="Center"/>
        <TextBlock x:Name="textBlock3" Background="#FF62BB46" Foreground="White" Text="3" Height="30" Grid.Row="2" FontSize="20" FontWeight="Bold" TextAlignment="Center"/>
    </Grid>
</Grid>
   [StackPanel]中的[网格]

<StackPanel>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="textBlock1" Background="#FF00AAE7" Foreground="White" Text="1" Height="90" FontSize="20" FontWeight="Bold" TextAlignment="Center"/>
        <TextBlock x:Name="textBlock2" Background="#FFF04937" Foreground="White" Text="2" Height="60" Grid.Row="1" FontSize="20" FontWeight="Bold" TextAlignment="Center"/>
        <TextBlock x:Name="textBlock3" Background="#FF62BB46" Foreground="White" Text="3" Height="30" Grid.Row="2" FontSize="20" FontWeight="Bold" TextAlignment="Center"/>
    </Grid>
</StackPanel>

注意:

在第二个代码中,我更改了前两个textBlocks的大小,以突出显示网格行的自动重新调整。

问题:

如果没有为网格行定义高度,为什么当网格位于堆叠面板内时它们会自动重新调整?为什么当网格位于另一个网格内时它们不会重新调整?

1 个答案:

答案 0 :(得分:3)

是。只需制作列Width="auto"和行Height="auto"

类似的东西:

<Grid.ColumnDefinitions>  
   <ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>  
<Grid.RowDefinitions>  
    <RowDefinition Height="auto" />
</Grid.RowDefinitions> 

编辑:由于您的问题已被修改。

在您的第一个代码段Grid默认情况下,如果未指定宽度/高度,则会让其子级占用所有可用空间。

在第二个代码段中,默认情况下StackPanel水平拉伸其子项(请注意,StackPanel.Orientation默认为垂直)。孩子(Grid)想要占用180个垂直空间,这是其所有孩子的总高度(TextBlock s)。最后,StackPanel为其子女保留了180个垂直空间。

您应该阅读WPF面板如何布置他们的孩子。 Panel Overview

相关问题