How to make WPF wrappanel child items to stretch?

Yeonho picture Yeonho · Nov 4, 2011 · Viewed 20k times · Source

I'd like to create an ItemsControl where child items are placed like a WrapPanel, but child Items should take as much space as it can. So that when the window size gets larger or smaller, the child items should stretch according to a certain width:height ratio. When the child items get added or removed from the ItemsControl's ItemsSource, the WrapPanel should place linebreaks among items appropriately to keep child item's width:height ratio.
Below is what I have so far. Is it possible to do this in Xaml? or should I create a custom control for this? Thanks in advance!

<Window>
<Grid>
    <ItemsControl ItemsSource="{Binding DataCollection}">
       <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
             <WrapPanel Orientation="Vertical"/>
          </ItemsPanelTemplate>
       </ItemsControl.ItemsPanel>
       <ItemsControl.ItemTemplate>
          <DataTemplate>
             <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Stretch">
                <StackPanel Orientation="Horizontal" >
                   <TextBlock TextWrapping="Wrap" Text="{Binding Name}" />
                   <TextBlock TextWrapping="Wrap" Text="{Binding Value}"/>
                   <TextBlock TextWrapping="Wrap" Text="{Binding Time,  StringFormat='hh:mm:ss' }"/>
                </StackPanel>
             </Border>          
         </DataTemplate>
       </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>
</Window>

Answer

Thomas Levesque picture Thomas Levesque · Nov 16, 2011

Use a UniformGrid rather than a WrapPanel. Just set the number of columns you want with the Columns property, and it should give you the desired result.