Search code examples
wpfbackgroundstackpanel

Why doesn't my StackPanel's background color stretch to fill the full width?


I have a StackPanel with a background brush, and it contains a single button. It is contained within a Grid that is wider than the button.

Frustratingly, the background is only as wide as the button. I can see it around the button's margin. So I end up having this wide bar of default-gray next to my button which has a border of my background color around it.

<StackPanel Visibility="Visible" HorizontalAlignment="Right" Background="{StaticResource qtyBg}">
    <Button x:Name="bttnQtyEditKeys" Content="EDIT KEYPAD" Visibility="Visible" Click="bttnQtyEditKeys_Click"/>
</StackPanel>

I was able to fix it by wrapping a Border around it, and setting the Border's background brush.

It's a hack, so it it annoys me. Is there an alternate way to make the StackPanel's background not be stupid?


Solution

  • The problem isn't your background, it's your StackPanel. Your background is fine, it's your StackPanel that isn't filling the available space.

    You need to set HorizontalAlignment and VerticalAlignment to Stretch on your StackPanel.

    This works fine for me:

    <Grid>
        <StackPanel Visibility="Visible" HorizontalAlignment="Stretch" Background="blue">
            <Button x:Name="bttnQtyEditKeys" HorizontalAlignment="Right" Content="EDIT KEYPAD" Visibility="Visible" Click="bttnQtyEditKeys_Click"/>
        </StackPanel>
    </Grid>