WPF: How to make controls stretch in a StackPanel?

Qwertie picture Qwertie · May 7, 2009 · Viewed 19.8k times · Source

A Slider and some other controls won't stretch to fill available space when placed in a StackPanel; instead the width is always MinWidth (or about 10 pixels if MinWidth is not set). How do I make it stretch (the equivalent of Anchor.Left|Anchor.Right in WinForms)? Example:

<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
    <Slider Value="14" SmallChange="0.5" Maximum="100" Minimum="4" 
            x:Name="FontSize" MinWidth="30" LargeChange="2" 
            TickFrequency="10" TickPlacement="TopLeft" 
            HorizontalAlignment="Stretch"/>
    <TextBlock Margin="8" Text="{Binding ElementName=FontSize, Path=Value}" 
               VerticalAlignment="Center"/>
</StackPanel>

Answer

Matt Hamilton picture Matt Hamilton · May 7, 2009

You want DockPanel instead:

<DockPanel DockPanel.Dock="Bottom" LastChildFill="True">
    <TextBlock DockPanel.Dock="Right" ... />
    <Slider ... />
</DockPanel>

DockPanel gets you the "Anchor" functionality you want. StackPanel simply stacks things next to each other.

I notice from your code block that your StackPanel is already docked inside a dockpanel, so I've included the same docking attribute in my code sample above.