如何使WPF StackPanel适合网格单元格

Con*_*nor 7 c# wpf wpf-controls stackpanel

我的WPF项目中有一个StackPanel控件,它位于Grid的第0列第2行.如何将StackPanel大小自动调整为该网格单元的大小?将StackPanel宽度和高度设置为"auto"只会将其大小调整为其内容.我可以明确地将其宽度和高度设置为数值,但我想知道是否有更清晰,更准确的方法.谢谢.

相关的XAML:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="74*"/>
        <RowDefinition Height="74*"/>
        <RowDefinition Height="421*"/>
    </Grid.RowDefinitions>
    <Label Content="{StaticResource LoginWindow_Title}" Style="{StaticResource TitleH1}" Grid.ColumnSpan="2"/>
    <Label Content="{StaticResource LoginWindow_Subtitle}" Style="{StaticResource TitleH2}" Grid.Row="1" Grid.ColumnSpan="2"/>
    <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Center" Grid.Row="2" VerticalAlignment="Top">
        <StackPanel HorizontalAlignment="Left" Grid.Row="2" VerticalAlignment="Top">
            <Label Content="Log in"/>
        </StackPanel>
    </Border>
</Grid>
Run Code Online (Sandbox Code Playgroud)

She*_*dan 7

答案总是一样的...... 不要StackPanel用于布局目的.它们主要用于排列不太可能改变大小的UI元素.即使您将大小调整StackPanel为正确的大小,也无济于事,因为StackPanel不会重新排列或调整其内容项的大小.如果你想要这个功能,你将不得不使用其他Panel控件之一Grid.


ice*_*bat 7

StackPanel不在,它在Grid里面Border.因此,要获取所有可用空间,您可以Stretch为它及其父级设置水平和垂直对齐Border:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="74*"/>
        <RowDefinition Height="74*"/>
       <RowDefinition Height="421*"/>
    </Grid.RowDefinitions>

    <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
            BorderBrush="Black" BorderThickness="1"  Grid.Row="2">
        <StackPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
            <Label Content="Log in"/>
        </StackPanel>
    </Border>
</Grid>
Run Code Online (Sandbox Code Playgroud)

即便如此,像其他提到的那样,在这种情况下,其他一些小组几乎肯定会更好.