How to collapse a RowDefinition?

You could have set RowDefinition.Height="Auto" and could have assigned fixed height to the actual visual in that row. This way when the visual is visibly collpased, the row does not occupy the fixed width that was assigned to the row defintion.


Setting RowDefinition.Height ="Auto" is not suitable for all cases, as often we want * sizing of our rows.

Rather than dynamically/programatically adding and removing rows from the list, it is easier and safer to stretch the first rows contents over the next row/s.

This can be done by using a DataTrigger to set Grid.RowSpan on the first item on the grid. Below is a complete example - just paste it into a new WPF window to see it in action.

  <Grid>
        <Grid.Resources>

            <BooleanToVisibilityConverter x:Key="visConverter"></BooleanToVisibilityConverter>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0" Background="Orange">
            <Grid.Style>
                <Style TargetType="Grid">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=toggle1, Path=IsChecked}" Value="False">
                            <Setter Property="Grid.RowSpan" Value="3"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Grid.Style>
        </Grid>
        <GridSplitter Grid.Row="1" ResizeBehavior="PreviousAndNext" HorizontalAlignment="Stretch" Height="3" 
                      Visibility="{Binding ElementName=toggle1, Path=IsChecked, Converter={StaticResource visConverter}}"></GridSplitter>
        <Grid Name="bottomGrid" Grid.Row="2" Background="LightBlue" 
              Visibility="{Binding ElementName=toggle1, Path=IsChecked, Converter={StaticResource visConverter}}">
        </Grid>
        <ToggleButton Name="toggle1" VerticalAlignment="Top">Hide/Show</ToggleButton>
</Grid>

It's absolutely okay to apply a style with triggers to your RowDefinition for the row you want to collapse. This can help when you have star values for your heights.

The following might be useful if you wanted to hide a results section before results existed (i.e. a zero-count ObservableCollection), for example.

<RowDefinition>
    <RowDefinition.Style>
        <Style>
            <Setter Property="RowDefinition.Height" Value="2*"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Results.Count}" Value="0">
                    <Setter Property="RowDefinition.Height" Value="0"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </RowDefinition.Style>
</RowDefinition>

Tags:

Wpf

Visibility