.NET MAUI Layouts
Layouts in .NET MAUI are fundamental to arranging user interface elements on the screen. They provide containers that manage the size and position of child elements, enabling flexible and adaptive UIs across different platforms and screen sizes.
Core Layout Concepts
.NET MAUI provides a variety of built-in layout controls, each with its own characteristics for arranging children:
StackLayout
The StackLayout arranges child elements in a one-dimensional line, either horizontally or vertically. It's a common choice for simple lists or sequences of controls.
Example: Vertical StackLayout
<StackLayout Orientation="Vertical" Spacing="10">
<Label Text="First Item" />
<Button Text="Click Me" />
<Image Source="my_image.png" />
</StackLayout>
Rendered View:
Grid
The Grid is a powerful layout control that arranges child elements in rows and columns. It allows for complex UIs with precise control over element placement and sizing.
Example: Simple Grid
<Grid RowDefinitions="Auto,*" ColumnDefinitions="*,Auto">
<Label Grid.Row="0" Grid.Column="0" Text="Header" FontSize="Large" />
<Image Grid.Row="1" Grid.Column="0" Source="logo.png" />
<Button Grid.Row="1" Grid.Column="1" Text="Action" />
</Grid>
Rendered View:
FlexLayout
FlexLayout arranges child elements in a flexible manner, similar to CSS Flexbox. It supports wrapping, alignment, and justification of items, making it ideal for responsive content.
Example: Horizontal FlexLayout with Wrapping
<FlexLayout Direction="Row" Wrap="Wrap" Justify="SpaceAround" AlignItems="Center">
<BoxView Color="SkyBlue" WidthRequest="80" HeightRequest="80" />
<BoxView Color="LightGreen" WidthRequest="100" HeightRequest="60" />
<BoxView Color="LightCoral" WidthRequest="70" HeightRequest="90" />
<BoxView Color="LightYellow" WidthRequest="90" HeightRequest="70" />
</FlexLayout>
Rendered View:
Common Layout Scenarios
- Lists and Items: Use
StackLayoutfor vertical lists orFlexLayoutfor more complex horizontal or grid-like item arrangements. - Forms and Dialogs:
Gridis excellent for aligning labels and input fields in forms. - Adaptive UIs: Leverage
GridandFlexLayoutwith responsive definitions or properties to adapt to different screen sizes and orientations.
Custom Layouts
For highly specific arrangement needs, you can create custom layout controls by inheriting from existing layout classes or implementing the ILayoutController interface.
Understanding and effectively using these layout controls is key to building robust and user-friendly .NET MAUI applications.