[英]Xamarin.Forms: How to center views using Relative Layout? `Width` and `Height` return -1
尝试在 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
和Width
返回 -1 ?Xamarin.Forms 返回 -1 作为这些属性的默认值,并保持 -1,直到 Xamarin.Forms 创建本机控件(例如 UIButton)并将该本机控件添加到布局中。
在此链接中,您可以看到 Xamarin.Forms 源代码返回-1
作为默认值: https : //github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/VisualElement.cs
使用局部函数动态检索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 - getWidth(parent, mySwitch)/ 2),
Constraint.RelativeToParent(parent => parent.Height / 2 - getHeight(parent, mySwitch) / 2));
//Add a Label below the switch
mainLayout.Children.Add(switchLabel,
Constraint.RelativeToParent(parent => parent.Width / 2 - getWidth(parent, switchLabel) / 2),
Constraint.RelativeToView(mySwitch, (parent, view) => view.Y + getHeight(parent, mySwitch) + 10));
Content = mainLayout;
static double getWidth(RelativeLayout parent, View view) => view?.Measure(parent.Width, parent.Height).Request.Width ?? -1;
static double getHeight(RelativeLayout parent, View view) => view?.Measure(parent.Width, parent.Height).Request.Height ?? -1;
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教我这个技巧!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.