Search code examples
c#xamlalignmentpanel

Not able to stretch an inner StackPanel


Usingthe setup below, I can color the whole width of the window purplish. The inner stack panel is chartreusian and shifted to the left.

<StackPanel HorizontalAlignment="Stretch"
            Orientation="Horizontal"
            Background="BlueViolet"
            Height="70">
  <StackPanel HorizontalAlignment="Left"
              Orientation="Horizontal"
              Background="Chartreuse" >

I was expecting that if I changed the horizontal alignment of the inner stack panel to streched, it'd fill out all the width as well but that doesn't happen. I've tried both right and streched alignments and it seems that it's not affecting the width of the inner control.

According to the posts I've found that is the way to achieve it (and it certainly worked for the outer control). What can I be missing? I've removed the other controls declared in the outer panel (i.e. all the siblings to the chartreusily colored one) with no difference.


Solution

  • A StackPanel will provide to its content as much space as required but also only as few as necessary.

    If you want to fill exactly the width of the window, just replace the outer StackPanel by a Grid

    If you want the StackPanel to fill at least the whole with, you can bind the MinWidth to its parent ActualWidth:

    <StackPanel HorizontalAlignment="Stretch"
        Name="parent"
        Orientation="Horizontal"
        Background="BlueViolet"
        Height="70">
    
        <StackPanel HorizontalAlignment="Stretch"
            MinWidth="{Binding Path=ActualWidth, ElementName=parent}"
            Orientation="Horizontal"
            Background="Chartreuse" >
        </StackPanel>
    </StackPanel>