Search code examples
xamarinxamarin.formsstacklayout

Setting relative height for Grid children


I'm adding 2 children to a Grid like this:

    private void pInitStackLayout()
    {
        grid1 = new Grid()
        {
        };

        grid2 = new Grid()
        {
        };

        biggrid = new Grid()
        {
            BackgroundColor = Color.Transparent,
            Margin = new Thickness(0),
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.StartAndExpand,
            Orientation = StackOrientation.Vertical,
        };
        biggrid.Children.Add(grid1,0,0);
        biggrid.Children.Add(grid2,0,1);

        this.Content = biggrid;
    }

The ContentPage's (which is a Navigation Page) Content is the biggrid.

I would like to make it so that grid1 takes up 80% of the available height, and grid2 takes up 20% (or the rest).

How could I achieve this?


Solution

  • It's very simple actually, just set the RowDefinitions of biggrid.

    // RowDefinitions isolated
    
    RowDefinitions = new RowDefinitionCollection
    {
        new RowDefinition { Height = new GridLength(8, GridUnitType.Star) },
        new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }
    }
    
    // RowDefinitions isolated
    
    // Actual code
    private void pInitStackLayout()
    {
        grid1 = new Grid()
        {
        };
    
        grid2 = new Grid()
        {
        };
    
        biggrid = new Grid()
        {
            RowDefinitions = new RowDefinitionCollection
            {
                new RowDefinition { Height = new GridLength(8, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }
            },
    
            BackgroundColor = Color.Transparent,
            Margin = new Thickness(0),
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.StartAndExpand,
            Orientation = StackOrientation.Vertical,
        };
        biggrid.Children.Add(grid1,0,0);
        biggrid.Children.Add(grid2,0,1);
    
        this.Content = biggrid;
    }