StackLayout
The StackLayout
is a layout container that arranges its child elements in a one-dimensional line, either horizontally or vertically. It's a fundamental and widely used layout in .NET MAUI for arranging controls in sequence.
Orientation
By default, StackLayout
arranges its children vertically. You can change this behavior by setting the Orientation
property:
StackOrientation.Vertical
(default): Arranges children from top to bottom.StackOrientation.Horizontal
: Arranges children from left to right.
Spacing
The Spacing
property controls the amount of space between child elements within the StackLayout
. This value is a density-independent pixel value.
Example Usage
Vertical StackLayout
<StackLayout Padding="10,0,10,0"
Spacing="10"
VerticalOptions="Center"
HorizontalOptions="Center">
<Label Text="Welcome to .NET MAUI!"
FontSize="24"
TextColor="DarkBlue"/>
<Button Text="Get Started"/>
<Image Source="dotnet_bot.png"/>
</StackLayout>
Horizontal StackLayout
<StackLayout Orientation="StackOrientation.Horizontal"
Spacing="20"
Padding="10">
<Image Source="icon_heart.png" HeightRequest="50"/>
<Label Text="Love .NET MAUI"
VerticalOptions="Center"
FontSize="18"/>
</StackLayout>
Properties Summary
Orientation
: Defines whether children are arranged vertically or horizontally.Spacing
: Sets the space between child elements.Padding
: Adds space inside the border of the layout.Children
: A collection of the child elements within the layout.
Best Practices
- Use
StackLayout
for simple, linear arrangements of elements. - For more complex layouts, consider using
Grid
orFlexLayout
. - Be mindful of nesting multiple
StackLayout
s, as it can impact performance on complex UIs. - Use
VerticalOptions
andHorizontalOptions
on the child elements to control their alignment within theStackLayout
.
Performance Considerations
While StackLayout
is efficient for most use cases, excessively deep nesting of StackLayout
s can lead to performance degradation. In such scenarios, consider refactoring your layout using Grid
or a single StackLayout
with more sophisticated child element arrangement.