Search code examples
xamlxamarin.formsandroid-relativelayout

Relative Layout XConstraint & YConstraint Vs. WidthConstraint & HeightConstraint in Xamarin.Forms


What's the difference between XConstraint and WidthConstraint or YConstraint and HeightConstraint when using Relative layout in Xamarin.Forms?
It seems like they both serve the same purpose and they can be used interchangeably. Here's an example from Microsoft's documentation.

<RelativeLayout>
<BoxView Color="Red" x:Name="redBox"
    RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,
        Property=Height,Factor=.15,Constant=0}"
    RelativeLayout.WidthConstraint="{ConstraintExpression
        Type=RelativeToParent,Property=Width,Factor=1,Constant=0}"
    RelativeLayout.HeightConstraint="{ConstraintExpression
        Type=RelativeToParent,Property=Height,Factor=.8,Constant=0}" />

<BoxView Color="Blue"
    RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView,
        ElementName=redBox,Property=Y,Factor=1,Constant=20}"
    RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView,
        ElementName=redBox,Property=X,Factor=1,Constant=20}"
    RelativeLayout.WidthConstraint="{ConstraintExpression
        Type=RelativeToParent,Property=Width,Factor=.5,Constant=0}"
    RelativeLayout.HeightConstraint="{ConstraintExpression
        Type=RelativeToParent,Property=Height,Factor=.5,Constant=0}" />
</RelativeLayout>

Solution

  • No, they are different.

    XConstraint – decide the x (horizontal) position of the view's anchor

    YConstraint – decide the y (vertical) position of the view's anchor

    WidthConstraint – decide the width of the view

    HeightConstraint – decide the height of the view

    Each of those values are set as a proportional value in RelativeLayout.