0

I have the following object:

new Grid {
    RowDefinitions =
    {
        new RowDefinition { Height = new GridLength(3, GridUnitType.Star) },
        new RowDefinition { Height = new GridLength(2, GridUnitType.Star) },
        new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }
    },
    ColumnDefinitions =
    {
        new ColumnDefinition { Width = new GridLength(3, GridUnitType.Star) },    
        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }
    },
    Children =
    {
        new Label { Text = "TRIP #5", FontFamily = Device.OnPlatform(null, "latoblack.ttf#Lato Black", null), FontSize = 16, TextColor = Color.White, HorizontalTextAlignment = TextAlignment.Start, Margin = new Thickness(0, 0, 0, 10) },
        new Label { Text = "Started 24/07/2017", FontFamily = Device.OnPlatform(null, "latolight.ttf#Lato Light", null), FontSize = 16, TextColor = Color.White, HorizontalTextAlignment = TextAlignment.Start },
        new Label { Text = "Is currently in progress", FontFamily = Device.OnPlatform(null, "latolight.ttf#Lato Light", null), FontSize = 16, TextColor = Color.White, HorizontalTextAlignment = TextAlignment.Start }
    }
}

I want to place the labels in positions (0,0), (0,1), (1,1) without having to use Children.Add. More specifically, I want to set the position of the labels to the positions that I mentioned directly from the object definition. How can I do that?

Thank you in advance!

Radu
  • 584
  • 1
  • 6
  • 30

1 Answers1

0

You can use Grid static methods Grid.SetRow, Grid.SetColumn etc. like so:

        var label = new Label { Text = "TRIP #5", FontSize = 16, TextColor = Color.Black, HorizontalTextAlignment = TextAlignment.Start, Margin = new Thickness(0, 0, 0, 10) };
        var grid = new Grid {
            RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(3, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(2, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }
            },
            ColumnDefinitions =
            {
                new ColumnDefinition { Width = new GridLength(3, GridUnitType.Star) },    
                new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }
            },
            Children =
            {
                label,
            }
        };

        grid.Padding = new Thickness(0,20,0,0);


        Grid.SetRow(label, 0);
        Grid.SetColumn(label, 0);
        Grid.SetColumnSpan(label,2);
        Grid.SetRowSpan(label, 3);

        this.Content = grid;
Milen
  • 8,697
  • 7
  • 43
  • 57
  • Isn't there any way that I can set the row/column position from inside the Grid object? – Radu Jul 25 '17 at 09:49
  • Well, another way is `myGrid.Children.Add(new Label { Text = "Row 1" }, 0, 0);` but that is clearly what you do not want to use :) – Milen Jul 25 '17 at 09:51