WPF XAML WrapPanel ListBox items in a row

zyjespox picture zyjespox · Jun 3, 2013 · Viewed 7.2k times · Source

I'm forced to ask for help, while I'm not able to figure it out by myself. I'm working on WPF-XAML desktop application, in which GUI is mostly generated dynamically.

My query regards styling of WrapPanel with ListBox items.

Please find a piece of code from my usercontrol (.xaml):

<DockPanel x:Name="xResultPanel">
  <ListView x:Name="bResultPanel" ItemsSource="{Binding ResultList, UpdateSourceTrigger=PropertyChanged}">
    <ListView.ItemTemplate>
      <DataTemplate>
        <Expander Header="{Binding GroupName}" Style="{DynamicResource FeatureExpander2}">
          <WrapPanel ItemWidth="140" Orientation="Horizontal">
            <ListBox x:Name="ListOfTiles" ItemsSource="{Binding VideoSamples}">
              <ListBox.ItemTemplate>
                <DataTemplate>
                  <StackPanel Width="120" Margin="10" HorizontalAlignment="Left">
                     <Image />
                     <TextBlock />
                  </StackPanel
                </DataTemplate>
              </ListBox.ItemTemplate>
            </ListBox>
          </WrapPanel>
        </Expander>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</DockPanel>

Above code returns ListBox items presented not in a row, but each item in new line. I tried to set MinWidth, Width etc for WrapPanel and ListBox, but with no result.

Thanks in advance for all related tips how to force WrapPanel to fill it's content horizontally.

Answer

Daniel Hilgarth picture Daniel Hilgarth · Jun 3, 2013

The problem is that your WrapPanel only has a single child: The ListBox. This means that the layouting is done by the ItemsPanel template of the ListBox.

Try this instead:

   <Expander Header="{Binding GroupName}" Style="{DynamicResource FeatureExpander2}">
      <ListBox x:Name="ListOfTiles" ItemsSource="{Binding VideoSamples}">
        <ListBox.ItemTemplate>
          <DataTemplate>
            <StackPanel Width="120" Margin="10" HorizontalAlignment="Left">
              <Image />
              <TextBlock />
            </StackPanel>
          </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemsPanel>
          <ItemsPanelTemplate>
            <WrapPanel />
          </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
      </ListBox>
    </Expander>