Search code examples
performancexamlmauistacklayout

Which StackLayout type should I use in MAUI?


As far as I've worked with MAUI, I have only ever been using <VerticalStackLayout/> and <HorizontalStackLayout/> to position child elements horizontally or vertically.

I rarely or pretty much never use <StackLayout/> as I read it might perform slightly worse.

When, if at all, is it recommended to use <StackLayout/> and adjust its Orientation attribute?

Should I use...

<StackLayout Orientation="Horizontal">
<StackLayout/>

<StackLayout Orientation="Vertical">
<StackLayout/>

...instead of...

<HorizontalStackLayout>
<HorizontalStackLayout/>

<VerticalStackLayout>
<VerticalStackLayout/>

...or the other way around, depending on different scenarios?


Solution

  • From a GitHub issue on MAUI (https://github.com/dotnet/maui/issues/6766) there is a simple explanation for performance on how the StackLayout will work compared to the HorizontalStackLayout and VerticalStackLayout.

    The simplest way to look at it would be to stick to this:

    1. If you know the orientation of the layout will not change then use HorizontalStackLayout or VerticalStackLayout depending on the orientation you need.

    2. If you need to change the orientation and it might change at runtime then use StackLayout E.G. <StackLayout Orientation="{Binding MyStackOrientation}">

    Since Xamarin Forms only had StackLayout, porting apps to MAUI is relatively easy as the code does not have to change, so also helps for backward compatibility - developers don't have to go around all their XAML updating their stack layouts.

    The official docs also mention StackLayout being less performant though there is no explanation. https://learn.microsoft.com/en-us/dotnet/maui/user-interface/layouts/horizontalstacklayout?view=net-maui-8.0