Why won't the WPF progressbar stretch to fit?

John NoCookies picture John NoCookies · Nov 18, 2012 · Viewed 8.5k times · Source

This is my original code:

<StackPanel Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Orientation="Horizontal">
        <ProgressBar Height="23" Name="searchProgressBar" Foreground="Blue" BorderBrush="#00000000" BorderThickness="1" VerticalAlignment="Top" HorizontalAlignment="Stretch"/>
        <TextBlock Text="asdf" Height="23"  Name="progressTextBlock" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Right"/>
</StackPanel>

The progressbar was very small, maybe 2 or 3 pixels wide, then there was the text block and empty space after. So I tried explicitly docking the elements to sides:

<DockPanel Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" >
            <ProgressBar DockPanel.Dock="Left" Height="23" Name="searchProgressBar" Foreground="Blue" BorderBrush="#00000000" BorderThickness="1" VerticalAlignment="Top" />
            <TextBlock DockPanel.Dock="Right" Text="asdf" Height="23"  Name="progressTextBlock" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Right"/>
</DockPanel>

No avail. I also tried modifying each solution by setting HorizontalAlignment="Stretch" on the progress bar, but there's no change. How do i stretch it to fill all the space there is after the text block has been rendered?

Answer

Adi Lester picture Adi Lester · Nov 18, 2012

Remove DockPanel.Dock="Left" from the ProgressBar and switch the order of the controls:

<DockPanel>
    <TextBlock DockPanel.Dock="Right" Height="23"  VerticalAlignment="Top" HorizontalAlignment="Right"/>
    <ProgressBar Height="23" VerticalAlignment="Top" />
</DockPanel>

By default, DockPanel has its property LastChildFill set to true, which will make the ProgressBar take the available space.