wpfitemscontrolresizewrappanelbinding-expressions

Bind the height of a grid row to it's contents in WPF


I have a grid with a few rows. In the top row, I have an ItemsControl that is bound dynamically to a collection and uses a DataTemplateSelector and ItemsPanelTemplate (with a single horizontally arranged WrapPanel). Here's a stripped-down version of what I have so far:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="2" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <GridSplitter Background="#666" Grid.Row="1" Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
    <ItemsControl x:Name="items" Background="#DDD" Grid.Row="0" ItemTemplateSelector="{StaticResource itemTemplateSelector}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</Grid>

Instead of setting that first row's height to 40, I'd like to set it dynamically based on the minimum height that the ItemsControl must be to fit all of its contents. Since the ItemsControl's height is being constrained by the Grid Row's height, I can't figure out which element I should be binding and to what element's property I should be binding it to.

It would make sense to bind the Grid Row's Height to the "desired height" of the ItemsControl. So, I found the DesiredSize property and bound my RowDefinition's Height to the ItemsControl's DesiredSize.Height. That works when it first loads, but does not update as I resize the control (remember, I'm using a WrapPanel as my ItemsPanelTemplate, so as I resize the window, the height of the ItemsControl should be changing).

Does anyone know if this kind of situation is even supported by the binding framework, or would I need to add event handler code to accomplish this?

Thanks.


Solution

  • Did you try setting height to Auto to achieve what you want:

    <RowDefinition Height="Auto"/>
    

    (or am i thinking too simple here.. ?)