当试图在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;
Height
and Width
?Xamarin.Forms返回-1作为这些属性的默认值,并且它保持为-1,直到Xamarin.Forms创建本机控件,例如UIButton,并将原生控件添加到布局中。
在此链接中,您可以看到将-1
作为默认值返回的Xamarin.Forms源代码:https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/VisualElement.cs
使用Local Function动态检索Width
和Height
属性
var mainLayout = new RelativeLayout();
//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;
double getSwitchWidth(RelativeLayout parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Width;
double getSwitchHeight(RelativeLayout parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Height;
double getLabelWidth(RelativeLayout parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Width;
double getLabelHeight(RelativeLayout parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Height;
Func<RelativeLayout, double>
使用Func
动态检索Width
和Height
属性
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;
//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教我这招!