Xamarin Forms StackLayout: How to set width / height of children to percentages

87,693

Solution 1

StackLayout doesn't go very well with varying heights in this scenario. The Xamarin Forms engines isn't as well rounded as the WPF engine at this point. Basically you have to go

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="7*" />
        <RowDefinition Height="3*" />
    </Grid.RowDefinitions>
    <Entry Grid.Row="0" VerticalOptions="Fill"></Entry>
    <Button Grid.Row="1" VerticalOptions="Fill">Click me</Button>
</Grid>

Also as a side note, only Grids can expand to the full width or height of its parent element. StackLayout's determine their maximum size by the sum of their children unless they are within a Grid and you put HorizontalOptions="Fill" and VerticalOptions="Fill".

The only other way you could accomplish this is to get the DeviceHeight and Width from the OS and manually set the Heights of your elements. A complex and usually flawed approach, which I don't recommend.

Solution 2

While you can do this with grid, there is more suitable layout for it AbsoluteLayout

You can set position proportions with this: AbsoluteLayout.LayoutBounds=".5,1,.5,.1"

Share:
87,693
sgarcia.dev
Author by

sgarcia.dev

My Name is Sergei Garcia, and I’m a Front-End Engineer (and aspiring UI/UX designer) who loves to write high performance, clean, maintainable code for web apps. My hobbies include reading blogs to keep up to the latest trends in coding technologies and tech gadgets, taking courses about new Front End tool that help me stay ahead of the curve, as well as working on my next blog entry on Medium. I like to dabble in back end technologies like Node.js &amp; Python, because my next goal is to transition into a Full-Stack Developer.

Updated on July 09, 2022

Comments

  • sgarcia.dev
    sgarcia.dev almost 2 years

    Is there a way to create a vertical stack layout with a button that takes 30% of of the parent, and a text input that takes 70% of the parent? Something like this:

    <StackLayout Orientation="Vertical">
        <Entry Height="70%"></Entry>
        <Button Height="30%">Click me</Button>
    </StackLayout>
    

    But this doesn't work. Only solution so far is creating a complete Grid item and using that. Are there no other solutions?