C# – How to Fit WPF StackPanel to Grid Cell

cstackpanelwpfwpf-controls

I have a StackPanel control in my WPF project, and it is in column 0 row 2 of a Grid. How can I autofit the StackPanel size to the size of that grid cell? Setting the StackPanel width and height to "auto" will just size it to its contents. I could explicitly set its width and height to numerical values, but I was wondering if there was a cleaner, more accurate way. Thank you.

Relevant 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>

Best Answer

Your StackPanel is not in Grid, it`s inside Border. So for it to take all available space you can set horizontal and vertical alignment to Stretch both for it and its parent 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>

Even so, like others mentioned, some other panel almost definetely will be better in this case.

Related Topic