Xamarin.Forms Images Causes Grid Row Height To Excessively Increase

Viewed 366

The grid is already instantiated with the columns at the start of the code outside the foreach loop, within this loop, rows are being instantiated.

foreach (var post in posts)
{
    Frame featuredFrame = new Frame();
    featuredFrame.Padding = 20;
    featuredFrame.Margin = new Thickness(0, 10, 0, 0);

    Label postTitle = new Label();
    postTitle.FontSize = Device.GetNamedSize(NamedSize.Subtitle, typeof(Label));

    BoxView titleSeparator = new BoxView();
    titleSeparator.Color = Color.Gray;
    titleSeparator.HeightRequest = 1;
    titleSeparator.HorizontalOptions = LayoutOptions.Fill;

    Image postFeaturedImage = new Image();
    postFeaturedImage.Source = ImageSource.FromUri(imageUri);
    postFeaturedImage.Aspect = Aspect.AspectFill;

    BoxView imageSeparator = new BoxView();
    imageSeparator.Color = Color.Gray;
    imageSeparator.HeightRequest = 2;
    imageSeparator.HorizontalOptions = LayoutOptions.Fill;

    Label publishDate = new Label();
    publishDate.FontSize = Device.GetNamedSize(NamedSize.Caption, typeof(Label));

    StackLayout postDetails = new StackLayout();
    postDetails.Children.Add(postTitle);
    postDetails.Children.Add(titleSeparator);
    postDetails.Children.Add(postFeaturedImage);
    postDetails.Children.Add(imageSeparator);
    postDetails.Children.Add(publishDate);
    postDetails.Margin = new Thickness(0);
    postDetails.Padding = new Thickness(0);

    featuredFrame.Content = postDetails;

    postGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
    postGrid.Children.Add(featuredFrame, columnNumber, rowNumber);
}

As you can see, the rows are being created with the height set to Auto, this should mean the rows are the same height as the children.

This is the result of the code above:

Result With Pictures

This is the result of the code above with postDetails.Children.Add(postFeaturedImage); commented out:

Result without pictures

In the screenshot with the images, there is a lot of blank space below the publish date-time text. In the screenshot without the images, this blank space is gone.

I need the pictures visible, but the blank space shouldn't be there. How can I fix this?

1 Answers

I ran into the same issue (that's how I found the question) and I have managed to fix it.

I solved the problem by adding VerticalOptions like this:

postDetails.VerticalOptions = LayoutOptions.Start;

and make sure that you have Height = GridLength.Auto for the RowDefinition.

Related