Xamarin Tutorial Part 6 - Grid in code

 Before you start with this blog, go to this syntax and tutorial blog. It will easy to understand the code of this blog.

Grid through cs code

Grid in xaml

Grid in xamarin

Please, support my blog by clicking on our sponsors ad!

Below code for grid in c# Code. This is recommended when it has to add at runtime. By default you can add grid through xaml, Because xaml is easy to code and understand.

    var grid = new Grid();

    var autoRow = new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) };
    var fixRow = new RowDefinition() { Height = new GridLength(200) };
    var starRow = new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) };

    var col1 = new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) };
    var col2 = new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) };
    var col3 = new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) };
    var col4 = new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) };

    grid.RowDefinitions.Add(autoRow);
    grid.RowDefinitions.Add(fixRow);
    grid.RowDefinitions.Add(starRow);

    grid.ColumnDefinitions.Add(col1);
    grid.ColumnDefinitions.Add(col2);
    grid.ColumnDefinitions.Add(col3);
    grid.ColumnDefinitions.Add(col4);

    BoxView boxView = new BoxView() { BackgroundColor = Color.Blue };

    grid.Children.Add(new BoxView { Color = Color.Green }, 0, 0); // column,row
    grid.Children.Add(new BoxView { Color = Color.Yellow }, 1, 0);
    grid.Children.Add(new BoxView { Color = Color.YellowGreen }, 2, 0);
    grid.Children.Add(boxView, 3, 0);
    Grid.SetRowSpan(boxView, 2);

    grid.Children.Add(new BoxView { Color = Color.Pink }, 0, 1);
    grid.Children.Add(new BoxView { Color = Color.Red }, 1, 1);
    grid.Children.Add(new BoxView { Color = Color.Orange }, 2, 1);


    var nestedGrid = new Grid()
    {
        RowDefinitions =
        {
            new RowDefinition(){Height = new GridLength(1,GridUnitType.Star)},
            new RowDefinition(){Height = new GridLength(1,GridUnitType.Star)},
        },
        ColumnDefinitions =
        {
                new ColumnDefinition(),
                new ColumnDefinition()
        }
    };

    nestedGrid.Children.Add(new BoxView { Color = Color.Green }, 0, 0);
    nestedGrid.Children.Add(new BoxView { Color = Color.Yellow }, 1, 0);
    nestedGrid.Children.Add(new BoxView { Color = Color.YellowGreen }, 0, 1);
    nestedGrid.Children.Add(new BoxView { Color = Color.Magenta }, 1, 1);
    grid.Children.Add(nestedGrid, 0, 2);
    Grid.SetColumnSpan(nestedGrid, 4);

    Content = grid;  

Hope this is helpful to you, please share your feedback in comment section, thanks for reading

Comments

Popular posts from this blog

Explore the UI libraries available for .NET MAUI at no cost.

Push Notification using Firebase in xamarin form (Android and IOS)

School UI Design using xamarin form