Simple grid with stack layout don't work in xaml, works in code

Hi everyone!

I'm new at Xamarin.Forms. I want to create simple grid with 3 rows, and 1 column. Grid row 1 should contain stack layout with text (and other staff later) and should be centered on the screen (both vertically and horizontally). So I created this xaml code:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Disckreet.Main">
    <Grid>
        <Grid.RowDefinitions>
          <RowDefinition Height="20" />
          <RowDefinition Height="*" />
          <RowDefinition Height="40" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <StackLayout Grid.Row="1" BackgroundColor="Aqua" VerticalOptions="Center" HorizontalOptions="CenterAndExpand">
            <Label Text = "Some text"/>
        </StackLayout>
    </Grid>
</ContentPage>

And this code produces this view:

image

My second approach was to make same view but programatically:

public static Page GetMainPage ()
        {   
            var grid = new Grid {
                RowDefinitions = new RowDefinitionCollection {
                    new RowDefinition{ Height = new GridLength (20) },
                    new RowDefinition{ Height = new GridLength (1, GridUnitType.Star) },
                    new RowDefinition{ Height = new GridLength (40) }
                },
                ColumnDefinitions = new ColumnDefinitionCollection {
                    new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }
                }
            };

            var stack = new StackLayout {
                BackgroundColor = Color.Aqua,
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                VerticalOptions = LayoutOptions.Center
            };

            stack.Children.Add (new Label {
                Text = "Some text"
            });

            grid.Children.Add (stack);
            Grid.SetRow(stack, 1);

            return new ContentPage {
                Content = grid
            };
        }

View from code produces this view:

image

And my question is: Am I doing something wrong or this is bugged?

I would like to use xaml, but if it's bugged what is best approach? Do some views in xaml and others in code or stick on one "code style" view approach?

I'm looking forward for your response and advices!

Take care,

MP.

Posts

  • MuhammadAyubMuhammadAyub USMember

    Dear sir, did you try setting the Grid.Column property as well?

Sign In or Register to comment.