Search code examples
c#wpfgridrow-height

WPF Grid with Row heights * not expanding to Grid's max height


My WPF Grid has 3 rows (Auto, *, *) and maxHeight set to 500. When there is no content for second or 3rd row, Grid still doesn't expand to its maxHeight.

XAML Code:

<Grid MaxHeight="500">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!-- Button occupies 30 px-->
    <Button Grid.Row="0" Content="SwitchGrid"/>
    <ContentControl Grid.Row="1" Content="{Binding DG1}"/>
    <ContentControl Grid.Row="2" Content="{Binding DG2}"/>
</Grid>
                                         

Problem Statement:

  • [Success] If both ContentControls are provided, they occupy equal space (~230 px) and Grid is shown to expand to MaxHeight=500 px.
  • [Failure] If either of the ContentControls are not provided, the other contentcontrol still occupies max ~230 px (this ContentControl can occupy 500 px, but due to Grid's restriction it occupies only 230 px and shows a scrollbar) and Grid doesn't expand to 500 px. Snoop reveals that one of the control control size is 0, but looks like Grid is still reserving space for it. I have seen this behavior even when the Grid is placed directly inside MainWindow, hence I dont this it is related to any other container.

What can I do to make sure Grid expands to MaxHeight if any of its children need it?

Thanks,

RDV


Solution

  • You can bind the row height to a string property..

    <Grid MaxHeight="500">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="{Binding Row1Height, FallbackValue=*}"/>
            <RowDefinition Height="{Binding Row2Height, FallbackValue=*}"/>
        </Grid.RowDefinitions>
    
        <!-- Button occupies 30 px-->
        <Button Grid.Row="0" Content="SwitchGrid"/>
        <ContentControl Grid.Row="1" Content="{Binding DG1}"/>
        <ContentControl Grid.Row="2" Content="{Binding DG2}"/>
    </Grid>
    

    Then you can update it whenever you want, for example..

    public DG1 DG1 {
        set{
            // ..
            Row1Height = value == null ? "0" : "*";
        }
        get{
            // ..
        }
    }