如何将按钮延伸到整个网格,XAML

8

I have a problem with stretching the button all over the grid.

My code look like this:

<Grid x:Name="LayoutRoot" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="2*"/>
        <RowDefinition Height="8*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <StackPanel Grid.Column="5" Grid.Row="1" Width="Auto" Height="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <Button Content="Search" Background="#FF13D38D" Click="searchButton_Click" FontSize="48"/>
    </StackPanel>
</Grid>

But it didn't work for me, and stretch the button all over the grid, I tried maxwidth/maxheight but it also didn't work correctly anyone has an idea?


9
移除 stackpanel 就可以解决你的问题 - stackpanel 只会占用最小的空间来容纳子控件(无论你设置它们的对齐方式是什么)。在 stackpanel 中的控件不会拉伸以填满父容器,但是在网格中的单元格会拉伸。 - Charleh
它很有帮助,非常感谢! - MNie
1
<Button Content="搜索" Background="#FF13D38D" Click="searchButton_Click" FontSize="48" Grid.Column="5" Grid.Row="1" />去掉 Width="Auto" Height="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 是因为这些属性会被 Grid 元素重新设置,而 H/V 对齐方式的默认值就是 "Stretch"。 - eran otzap
1
如果问题得到解决,请自己将其添加为答案并接受它,而不是将其添加到问题中。 - Rndm
1个回答

11

简而言之:
移除 StackPanel(参见问题下面的Charleh的评论)。

问题已解决

<Grid x:Name="LayoutRoot" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="2*"/>
        <RowDefinition Height="8*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Content="Search" Background="#FF13D38D" Click="searchButton_Click" FontSize="48" Grid.Column="5" Grid.Row="1"/>
</Grid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接