How do I make an ItemsControl stretch to fill all available space?

kleineg picture kleineg · Apr 15, 2016 · Viewed 8k times · Source

I have an ItemsControl, with its ItemsSource bound to a list of items. The size of each of the items is as small as they can be, what I need is for the control and the items in the control to stretch to fit all available space.

I tried setting VerticalAlignment to Stretch on both the control, and its items (using a style). I also tried wrapping the ItemsControl in a DockPanel, and docking the ItemsControl to the bottom. How do I have the ItemsControl dynamically resize?

Also some, but not all, of the item's visibilities are set to Collapsed (through the same style). Will that be a factor in how this needs to be done?

<DockPanel HorizontalAlignment="Stretch">
    <ItemsControl DockPanel.Dock="Bottom"
                    ItemsSource="{Binding Owner.LoadPointCharts}"
                    HorizontalAlignment="Stretch"
                    x:Name="ItemsControl">
        <ItemsControl.ItemContainerStyle><!--Height="{Binding Path=Height, RelativeSource={RelativeSource AncestorType={x:Type DockPanel}}}"-->
            <Style TargetType="ContentPresenter">
            <Setter Property="VerticalAlignment"
                    Value="Stretch" />

                <Setter Property="Visibility">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource CompareIndexToVisibilityConverter}">
                        <Binding Path="Index" />
                        <Binding Path="SelectedIndex" />
                    </MultiBinding>
                </Setter.Value>
            </Setter>
            </Style >
        </ItemsControl.ItemContainerStyle>
        </ItemsControl>
</DockPanel> 

Answer

Florian Lavorel picture Florian Lavorel · Jul 27, 2018

The accepted answer is a little too complex in my opinion. Also setting the positions of your items in a Grid can be annoying. UniformGrid is what you need.

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>