Xamarin.Forms:如何使用相对布局居中视图? `Width`和`Height`返回-1

当尝试在Xamarin.Forms中使用控件的HeightWidth属性时,都返回-1,这会导致相对布局在屏幕上偏离中心。

 var mainLayout = new RelativeLayout(); //Add the Switch to the center of the screen mainLayout.Children.Add(mySwitch, Constraint.RelativeToParent(parent => parent.Width / 2 - mySwitch.Width / 2), Constraint.RelativeToParent(parent => parent.Height / 2 - mySwitch.Height / 2)); //Add a Label below the switch mainLayout.Children.Add(switchLabel, Constraint.RelativeToParent(parent => parent.Width / 2 - switchLabel.Width / 2), Constraint.RelativeToView(mySwitch, (parent, view) => view.Y + mySwitch.Height + 10)); Content = mainLayout; 

在此处输入图像描述

为什么Xamarin.Forms为HeightWidth返回-1?

Xamarin.Forms返回-1作为这些属性的默认值,并且它保持为-1,直到Xamarin.Forms创建本机控件,例如UIButton,并将该本机控件添加到布局。

在此链接中,您可以看到Xamarin.Forms源代码返回-1作为默认值: https : //github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/VisualElement.cs

使用相对布局来约束视图的最佳方法

使用Func动态检索“ Width和“ Height属性

 var mainLayout = new RelativeLayout(); Func getSwitchWidth = (parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Width; Func getSwitchHeight = (parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Height; Func getLabelWidth = (parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Width; Func getLabelHeight = (parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Height; //Add the Switch to the center of the screen mainLayout.Children.Add(mySwitch, Constraint.RelativeToParent(parent => parent.Width / 2 - getSwitchWidth(parent)/ 2), Constraint.RelativeToParent(parent => parent.Height / 2 - getSwitchHeight(parent) / 2)); //Add a Label below the switch mainLayout.Children.Add(switchLabel, Constraint.RelativeToParent(parent => parent.Width / 2 - getLabelWidth(parent) / 2), Constraint.RelativeToView(mySwitch, (parent, view) => view.Y + getSwitchHeight(parent) + 10)); Content = mainLayout; 

在此处输入图像描述

感谢@BrewMate教我这招!