简体   繁体   中英

Xamarin Create square layout using screen size

I have a problem. I want to create a StackLayout that has the width and height of the screen size, so it will be a square. I already tried this:

public Page1()
{
    InitializeComponent();

    imageLayout.HeightRequest = Application.Current.MainPage.Width;
    imageLayout.WidthRequest = Application.Current.MainPage.Width;
}

But that gave me the error that Application.Current.MainPage is null.

How can I fix this?

I think I would use the SizeChanged Event from your page:

public Page1()
{
    InitializeComponent();

    SizeChanged += (s,a) =>
    {
        imageLayout.HeightRequest = this.Width;
        imageLayout.WidthRequest = this.Width;
    };

}

You should override OnSizeAllocated for these purposes.

protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);
        imageLayout.WidthRequest= width;
        imageLayout.HeightRequest = width;
    }

Much cleaner way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM