1
votes

I'm new to Xamarin Forms and I'm stuck trying to make StackLayout work inside an AbsoluteLayout. There are 2 children inside my StackLayout: an Image (300x300 random image) and a Label. I'll show an example that illustrates my problem.

The following code works just fine for me (i'm using a 300x300 image) :

public class TestedPage : ContentPage
{
    public TestPage()
    {
    BackgroundColor = Color.Brown;
    StackLayout stl = new StackLayout();
    AbsoluteLayout ab = new AbsoluteLayout();

    Image img = new Image();
    img.Source = ImageSource.FromFile("circle.png");

    Label lbl = new Label
    {
        Text = "#Text1000",
        TextColor = Color.White,
        FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
        HorizontalOptions = LayoutOptions.Center
    };

    stl.Children.Add(img);
    stl.Children.Add(lbl);

    ab.Children.Add(stl);

    Content = ab;
    }
}

The problem is that the above code simply will throw 'stl' in it without positioning, which is big deal for me because I need it to be positioned exactly where I want. So, you may ask "why don't you use more parameters for Children.Add() ?", well ab.Children.Add(stl, new Rectangle(0,0,450,450)); will not position 'stl' correctly, for me at least, in the above code, it will be at start of screen and a bit after center, to the right, and not origin(0,0). Also, curious that I debugged and found out that Stack, Image and Absolute all have different height and width. Above code gives me 450, 450 for 'stl' (which is fine); 616, 360 for 'ab'; 150, 450 for 'img'.

So, is there anything I'm missing here ? It is a little confusing for me because I get it to work but it's a little "buggy", does not behave as I expected. Since I'm not experienced in Xamarin Forms I believe I'm missing something important here, which is why I hope you guys might give me some clues.

Any ideas ?

Any help is appreciated. Thanks!

1

1 Answers

1
votes

You might try:

AbsoluteLayout.SetLayoutFlags(stl, AbsoluteLayoutFlags.All);

AbsoluteLayout.SetLayoutBounds(stl, new Rectangle(0f, 0f, 1f, 1f));