17

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>
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
derGral
  • 1,836
  • 4
  • 19
  • 29

2 Answers2

30

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}"/>

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
NotDan
  • 31,709
  • 36
  • 116
  • 156
  • That seems to work; thanks! The problem is there are other things in the stackpanel and their widths are not taken into account. Any ideas for handling that? – derGral Oct 30 '09 at 19:21
  • Maybe you should use a grid or DockPanel instead? Or you could use a multibinding and a binding converter to do some custom logic. – NotDan Oct 31 '09 at 02:26
  • 13 years later, thank you. This helped me today and yeah, it worked. :D – codenamezero Apr 28 '23 at 00:44
9

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.
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Drew Marsh
  • 33,111
  • 3
  • 82
  • 100