How to set Height of items in XAML so they always occupy the same proportion of available space in parent ItemsControl?

itemscontrol, wpf, xaml

Solution

You could use a `UniformGrid` as your `ItemsPanelTemplate` and bind the `Rows` property to the number of items in your `ItemsControl`, like so:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="{Binding Items.Count, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

I did not test this code, so you need to check it, but I think the idea is clear.

EDIT: As pointed out by John below, this code is even easier:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="1" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

Problem

I have an ItemsControl with the following ItemTemplate: ``` <DataTemplate x:Key="myItemTemplate"> <TextBlock Height="???" Text="{Binding Path=Description}" /> </DataTemplate> ``` My question is, how do I set the Height of the TextBlock in the template so that it automatically assumes `ItemsControl.Height div ItemsCount` amount of vertical space? When there's only one item, I'd like it to be the full height of container, when there're two, each should be half the size, and so on. If possible, I'd prefer to do this completely in XAML to keep my ViewModel clean of UI logic.

Original source