当试图在Xamarin.Forms中使用控件的Height
和Width
属性时,都返回-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;
Run Code Online (Sandbox Code Playgroud)