我在StackLayout嵌套的RelativeLayouts有一个奇怪的问题,似乎StackLayout计算其元素的宽度应该是使用RelativeLayout宽度,然后RelativeLayout再次重新计算它.这导致子控件是相对宽度的平方,但是下列控件被放置在相对宽度.
这是一个bug还是我做错了?
例
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="MyClass" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" > <StackLayout Orientation="Horizontal" BackgroundColor="Blue"> <RelativeLayout> <ContentView BackgroundColor="Red" RelativeLayout.XConstraint= "{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0}" RelativeLayout.WidthConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=0.707106}" RelativeLayout.YConstraint= "{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0}" RelativeLayout.HeightConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=1}"> </ContentView> </RelativeLayout> <RelativeLayout> <ContentView BackgroundColor="Green" RelativeLayout.XConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=0.5}" RelativeLayout.YConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=1}"> </ContentView> </RelativeLayout> </StackLayout> </ContentPage>
解决方法
两个RelativeLayout元素可能是一个混乱的因素,并且每个被指定为相对于父StackLayout处于X位置0的事实,这似乎是一个冲突.
从注释中可以看出,如果每个RelativeLayout预期为父StackLayout的宽度的一半,则可以通过删除RelativeLayout元素之一来简化布局.
然后可以将子条的指定宽度除以2,使得每个的宽度相对于父StackLayout是相同的,并且相对于父对象设置的X位置也是水平位置.
这是我想出来的:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="App1.HomePage" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" > <StackLayout Orientation="Horizontal" BackgroundColor="Blue"> <RelativeLayout> <ContentView BackgroundColor="Red" RelativeLayout.XConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=0}" RelativeLayout.WidthConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=0.35}" RelativeLayout.YConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=0}" RelativeLayout.HeightConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=1}"> </ContentView> <!-- </RelativeLayout> <RelativeLayout> --> <ContentView BackgroundColor="Green" RelativeLayout.XConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=0.5}" RelativeLayout.WidthConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=0.25}" RelativeLayout.YConstraint= "{ConstraintExpression Type=RelativeToParent,Factor=1}"> </ContentView> </RelativeLayout> </StackLayout> </ContentPage>
这会产生更接近预期的东西吗?