我的目标是拥有一个包含两列控件的网格面板(每列将包含一个垂直 StackPanel),其中两列的宽度相同,但会根据它们包含的控件自动调整大小。因此,两个列的宽度都将等于任一列中最宽的控件。
我试过这样做:
<Grid HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="This is a wide button" HorizontalAlignment="Center" />
<Button Grid.Column="1" Content="Button" HorizontalAlignment="Center" />
</Grid>
这里的问题是列宽不相等。效果就好像我为列定义指定了 Width="Auto"
一样。如果网格的 HorizontalAlignment 为 Stretch 而不是 Center,则使用 * 宽度只会使列宽度相等。 (除非这些列不再根据内容自动调整大小。)
我错过了什么吗?有没有办法根据网格单元格中的内容获得相等大小的列宽?在 UWP 应用中(所以 UniformGrid 之类的东西不可用)?
最佳答案
那是因为你设置了 HorizontalAlignment
为 "Center", Grid 不会占据整个页面只占据中心部分(它的水平空间取决于子元素的总和,在这种情况下它不会加起来填充整页。
只需更改 HorizontalAlignment = "Stretch"
,以便整个可用空间和单个网格组件占据一半空间。
<Grid HorizontalAlignment="Stretch" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Content="This is a wide button"
HorizontalAlignment="Center" />
<Button Grid.Column="1"
Content="Button"
HorizontalAlignment="Center"/>
</Grid>
图片:
关于xaml - UWP XAML : How to get an auto-sized Grid with equal column widths,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52559523/