Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WrapPanel not wrapping when in a StackPanel with Horizontal orientation

The labels in the example below (WPF/XAML) just parade off the screen, no wrapping occurs. Removing the orientation works, but doesn't provided the needed functionality/look & feel. Any ideas how to make the WrapPanel wrap to the current size of the StackPanel?

<Window Height="300" Width="600">
    <StackPanel Orientation="Horizontal">
        <WrapPanel>
            <Label Height="28" Name="label1" Width="120">First Name</Label>
            <Label Height="28" Name="label2" Width="120">John</Label>
            <Label Height="28" Name="label3" Width="120">Last Name</Label>
            <Label Height="28" Name="label4" Width="120">Smith</Label>
            <!-- ...more labels!... -->
        </WrapPanel>
        <!-- ...other controls/panels... -->
    </StackPanel>
</Window>
like image 511
derGral Avatar asked Oct 26 '09 22:10

derGral


People also ask

How to use WrapPanel in wpf?

WPF WrapPanel control is a panel that positions child elements in sequential position from left to right by default. If child elements that are stacked don't fit in the row or column they are in, the remaining elements will wrap around in the same sequence.

What is wrap panel?

The WrapPanel control positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box. Subsequent ordering happens sequentially from top to bottom or from right to left, depending on the value of the Orientation property.

What is the use of StackPanel in WPF?

A StackPanel allows you to stack elements in a specified direction. By using properties that are defined on StackPanel, content can flow both vertically, which is the default setting, or horizontally.


2 Answers

You can bind the WrapPanel's MaxWidth to the StackPanel's ActualWidth.

I haven't tried this, but basically:

<WrapPanel MaxWidth="{Binding ActualWidth, ElementName=myStackPanel}"/>

like image 149
NotDan Avatar answered Sep 23 '22 21:09

NotDan


What you're doing isn't possible because of the algorithm that StackPanel uses when doing horizontal layout. It's basically going to ask each child element how big it wants to be and however much space it asks for it's going to give it.

You would either need to:

  1. Set a Width or MaxWidth on the WrapPanel.
  2. Use a WrapPanel as the outer panel in place of the StackPanel.
like image 35
Drew Marsh Avatar answered Sep 24 '22 21:09

Drew Marsh