Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

How to caluclate value in xaml Constraint Expression?

I'm trying to center a frame in a Relative Layout. To to this, I'd like to take the width of the parent, divide it by two and set its value as the XConstraint of the frame. Is there a way to calculate this in xaml? I'd like to avoid a mix of xaml views and views generated by code in my application.

Thanks in advance.


  • NMackayNMackay GBInsider, University admin


    You should be able to do this with Factor in XConstraint, I use this code to center a activity indicator in a grid within a relativelayout & scrollview.

    <ScrollView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
       <RelativeLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                                RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}">
                            <ActivityIndicator IsRunning="{Binding Busy}"
                                          IsVisible="{Binding Busy}"
                                          RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent,
                                          RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,
                                                                         Property=Height, Factor=0.5}">
                                <OnPlatform x:TypeArguments="Color"
                                            iOS="#39757F" />

    You might need to change the factor based on the OS (you shouldn't have to) but I can't think of a nice way to do that in XAML as XamlC still throws a wobbly (see below).

                <convert:RadSelectedltemEventArgsConverter x:Key="SelectedltemArgsToBinding" />
                <OnPlatform x:TypeArguments="x:Double" iOS="0.5" Android="0.44" x:Key="ActivityXFactor" />

    If anyone has a nice XAML only workaround then please share :smile:

Sign In or Register to comment.