Xamarin Forms Grid Layouts

I'm having a hard time setting the text and images on the grid. Here is what I need to do:

  • Two Columns
  • First column contains two rows of text, left-aligned.
  • Second column contains a single image, occupying the entire height, but right-aligned.

So it would essentially look like this:

enter image description here

I've tried two approaches.

  • The first approach was creating a 2x2 grid, and setting the ColumnSpan of the image to 2. But the icon was not centered vertically, it was still in the top row.

  • The second approach was creating a 1x2 grid (1 row, 2 columns), then add a StackLayout containing the two text strings to the first child, and the image to the second child. This time the image was centered vertically, but unfortunately left-aligned.

Can anyone help out, please?

Thank you.

Code for the second approach:

        Content = new Grid
        {
            //Padding = new Thickness(75, 5, 25, 5),
            VerticalOptions = LayoutOptions.FillAndExpand,
            HorizontalOptions = LayoutOptions.StartAndExpand,

            RowDefinitions =
            {
                new RowDefinition(),
            },

            ColumnDefinitions =
            {
                new ColumnDefinition(),
                new ColumnDefinition(),
            },
        };

        (Content as Grid).RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
        (Content as Grid).ColumnDefinitions[0].Width = new GridLength(9, GridUnitType.Star);
        (Content as Grid).ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star);

        StackLayout left = new StackLayout
        {
            HorizontalOptions = LayoutOptions.StartAndExpand,
            VerticalOptions = LayoutOptions.Center,
            Orientation = StackOrientation.Vertical,
            Children =
            {
                firstName,
                lastName,
            }
        };

        StackLayout right = new StackLayout
        {
            HorizontalOptions = LayoutOptions.Start,
            VerticalOptions = LayoutOptions.Center,
            Orientation = StackOrientation.Horizontal,
            Children =
            {
                icon,
            }
        };

        (Content as Grid).Children.Add(left, 0, 0);
        (Content as Grid).Children.Add(right, 1, 0);
        //(Content as Grid).Children[1].HorizontalOptions = LayoutOptions.End

This now looks like this:

enter image description here

The image should be in the far right side of the grid.

Thanks.

1 answer

  • answered 2017-08-16 19:26 Jason

    in your #2 example, the "right" StackLayout has HorizontalOptions.Start, which means it will be left aligned. You probably want to have it fill it's container, then right-align the image within it. Or get rid of the StackLayout altogether