views:

110

answers:

2

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.

+2  A: 

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>
gehho
Actually, it's simpler than that. UniformGrid will take care of the Row count for you automatically if you set Columns="1". And you need to use ItemsControl.ItemsPanel for this instead of ItemTemplate.
John Bowen
Oh, this is cool. I did not know about that. Thanks for the tip!And thanks for pointing out the "bug" in my sample code. I accidentally wrote "ItemTemplate" instead of "ItemsPanel". Fixed it in the above message.
gehho
A: 

I'm going to try and remember this as an intellectual exercise as I'm very new to WPF. I have no doubt I'll be corrected in due course. I think that you can specify a constant proportion by appending a % sign to the Height value i.e. Height="50%". This is deceptive, as it will add up all the numeric values of the heights of elements inside the parent, and size each one as its proportion of this sum. For example, three textblocks each of height="50%" would each have a height (50/150)*height of datatemplate = 1/3.

Tom W
I suppose, you are thinking of a "star-sized" Grid, but that won't work here because the number of rows is not known and not fixed. Well, there might be a working solution, but I think it is a lot more work.
gehho