Dynamic RowDefinition Height

24,133

Solution 1

Don't use the star notation, use Auto for your RowDefinitions. If the TextBlock.Text is empty, set the Visibility of the TextBlock to Visibility.Collapsed. The grid row will then automatically shrink to nothing.

Solution 2

This is not the answer to your question, just some info.

The * in the Height (or width for columns) means that the row (or column) width Height="*" (or Width="*") will take up the rest of the space. So if you have a grid with 4 rows in a grid with Height="100", if you do this:

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

The row width Height="*" will be 70 DIUs (device independent units).

Adding a number before the asterisk (Height="2*") only works if there are more than one rows using the asterisk, the number before the asterisk indicates how much more space will that specific row take (2* = twice as much, 3* three times as much, so on...). I. E.:

<Grid.RowDefinitions>
            <RowDefinition Height="10" />
            <RowDefinition Height="10" />
            <RowDefinition Height="2*" /> <!-- this row will be twice as tall as the one below -->
            <RowDefinition Height="*" />
</Grid.RowDefinitions>

Here the 3rd row will have a height of 54 DIUs (twice as much as the 4th row which has a height of 26 DIUs approx.), both heights sum 80, which is the rest of the space of the grid (10 + 10 + 26 + 54 = 100, the grid height).

BTW, I agree with Charlie's answer.

Share:
24,133
James
Author by

James

Java/C# Developer

Updated on August 09, 2020

Comments

  • James
    James almost 4 years

    I have a simple xaml control with the following Grid Row definition:

    <Grid.RowDefinitions>
                <RowDefinition Height="15*" />
                <RowDefinition Height="60*" />
                <RowDefinition Height="20*" />
                <RowDefinition Height="20*" />
                <RowDefinition Height="15*" />
    </Grid.RowDefinitions>
    

    Rows 1-3 each hold a text block which may or may not have text in it. In the code behind I want to minimise the RowDefinition if there is no text. Essentially I have the following in my code behind:

    if(textblock.Text != ""){
       grid.RowDefinitions[elementRow].Height = new GridLength(20, GridUnitType.Star);
    }
    else{
       grid.RowDefinitions[elementRow].Height = new GridLength(0, GridUnitType.Star);
    }
    

    I want rows 0 and 4 to stay as they are defined in the xaml. Unfortunatly this does not work even though there is text in the text block on row 2 nothing is displayed.

    Am I doing something wrong.

    Any help is appreciated,

    James