WPF:
是否有办法使网格的行(或列)的宽度和高度完全符合其内容的尺寸?
编辑:
网格中的网格
<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的大小,以突出显示网格行的自动调整。
问题:
当没有为网格的行定义高度时,为什么当网格位于堆栈面板中时它们会自动重新调整,以及为什么当网格在另一个网格中时不重新调整?
发布于 2017-04-18 01:16:42
是。只需创建列Width="auto"和Row Height="auto"即可。
类似于:
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
</Grid.RowDefinitions> 编辑:既然你的问题被修改了。
在您的第一个代码片段中,默认情况下,如果没有指定的宽度/高度,Grid将允许其子程序占用所有可用空间。
在第二个代码片段中,默认情况下,StackPanel水平地扩展它的子代码(注意,默认情况下,StackPanel.Orientation是垂直的)。子空间(Grid)要占用180个垂直空间,即所有子空间(TextBlocks)的总高度。最后,StackPanel为它的孩子保留了180个垂直空间。
您应该阅读WPF面板是如何布局其子面板的。面板概述。
https://stackoverflow.com/questions/43461643
复制相似问题