WPF: How to make controls stretch in a StackPanel?

谁说胖子不能爱 提交于 2019-12-03 14:54:58

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/832216/wpf-how-to-make-controls-stretch-in-a-stackpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!