Why does Xamarin.Forms return -1 for Height and Width ?
Xamarin.Forms returns -1 as the default value for these properties and remains -1 until Xamarin.Forms creates its own control, such as UIButton, and adds this own control to the layout.
From this link you can see the source code of Xamarin.Forms, returning -1 as the default value: https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/VisualElement.cs
The best way to use relative layouts to limit viewing
Option 1. Local functions (requires C # 7.0 or higher)
Use a local function to dynamically obtain the Width and Height properties.
var mainLayout = new RelativeLayout();
Option 2: Func<RelativeLayout, double>
Use Func to dynamically get Width and Height properties
var mainLayout = new RelativeLayout(); Func<RelativeLayout, double> getSwitchWidth = (parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Width; Func<RelativeLayout, double> getSwitchHeight = (parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Height; Func<RelativeLayout, double> getLabelWidth = (parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Width; Func<RelativeLayout, double> getLabelHeight = (parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Height;

Thanks @BrewMate for teaching me this trick!
source share