Question

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>
Was it helpful?

Solution

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.

OTHER TIPS

The answer is always the same... don't use a StackPanel for layout purposes. They are primarily used to arrange UI elements that are very unlikely to change size. Even if you resized the StackPanel to the correct size, it would not help because a StackPanel does not rearrange or resize it's content items. If you want this functionality, you'll have to use one of the other Panel controls like a Grid instead.

<Grid>
  <Border>
    <StackPanel VerticalAlignment="Center" ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top