如何使用RelativeLayout针对不在顶部的元素定位元素?

时间:2018-06-02 21:32:43

标签: xamarin.forms

我试图使用相对布局来定位多个元素。最顶层的元素相对于父元素定位,紧邻元素下方的元素具有其元素。 YConstraint由第一个元素的高度设置:

RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView,
ElementName=TopElement,Property=Height, Factor=1, Constant=0}">

但是,让我们说我想在第二个元素的正下方添加第三个元素。如何使用ConstraintExpression设置YConstraint?在XAML中,有没有办法根据前两个元素的高度之和来设置它?如果没有,我怎么能实现这个目标? (我不能使用StackPanel)

1 个答案:

答案 0 :(得分:1)

不幸的是我们无法在XAML中设置这样的约束。但是,我们可以通过编程方式实现它:

<强> XAML:

<RelativeLayout x:Name="RelativeLayout" BackgroundColor="White">
    <BoxView x:Name="BoxView1" BackgroundColor="Red"
             RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=0}"
             RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=0.1, Constant=0}"
             RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1, Constant=0}"/>

    <BoxView x:Name="BoxView2" BackgroundColor="Green"
             RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=BoxView1, Property=Height, Factor=1, Constant=0}"
             RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=0.1, Constant=0}"
             RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1, Constant=0}"/>

    <BoxView x:Name="BoxView3" BackgroundColor="Blue"/>
</RelativeLayout>

<强>代码隐藏:

protected override void OnAppearing()
{
    base.OnAppearing();
    RelativeLayout.Children.Add(BoxView3, Constraint.RelativeToParent(parent =>
    {
        return parent.X;
    }), Constraint.RelativeToView(BoxView2, (parent, sibling) =>
    {
        return sibling.Y + sibling.Height;
    }), Constraint.RelativeToParent((parent) =>
    {
        return parent.Width;
    }), Constraint.RelativeToParent((parent) =>
    {
        return parent.Height * .1;
    }));
}

enter image description here