0

I have a WPF grid with 3 rows that I would like size proportionately, unless one or more of the columns has no content. Each row currently has a gridview, and if there are no rows, I'd like to equally size the other 2 columns. If only one row has data, I'd like that row to take up all the space.

Equal Height Rows:

Equal Height Rows

Equal Height for only 2 Rows with Data

Equal Height for only 2 Rows with Data

My current Grid Definition is as follows:

<Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

This will clearly equally distribute the height for all 3 columns. I'm wondering how I can dynamically use Auto and * sizing on the same column depending if data is present or not.

Nick
  • 138,499
  • 22
  • 57
  • 95

1 Answers1

0

As per my understanding Grid is a container, which means Grid are rendered before actual content. Technically it would not be possible to set dynamic height/width according to content (unless you set to auto). Normally this situation can be overcome by controlling width/height of control instead of solving complex solution. In simple words lets say if you have 3 controls, and any of 2 has to be rendered, which has to equally occupy page width/height, you can set grid row height to auto, while set content height. You can use ActualWidth of parent control for reference.

Here is sample example for reference. In this example I assume that you have some mechanism which guides grid how many user controls are visible right now. so pass items count in converterParameter.

 public class HeightConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int.TryParse(parameter.ToString(), out var items);
        double.TryParse(value.ToString(), out var actualheight);
        return actualheight / items;
    }
         //......    
  }

 <Window.Resources>
    <local:HeightConverter x:Key="HeightConverter"/>
</Window.Resources>
<Grid x:Name="mainGrid" Background="Gray">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>

    </Grid.RowDefinitions>
    <local:sampleControl Background="Red" Grid.Row="0" Height="{Binding ElementName=mainGrid, Path=ActualHeight, Converter={StaticResource HeightConverter}, ConverterParameter=3}"/>
    <local:sampleControl Background="Yellow" Grid.Row="1" Height="{Binding ElementName=mainGrid, Path=ActualHeight, Converter={StaticResource HeightConverter}, ConverterParameter=3}"/>

    <local:sampleControl Background="Blue" Grid.Row="2" Height="{Binding ElementName=mainGrid, Path=ActualHeight, Converter={StaticResource HeightConverter}, ConverterParameter=3}"/>

</Grid>
Kamran Asim
  • 670
  • 4
  • 16