Chapter 4: Creating User Interfaces in .NET MAUI

This chapter introduces how to design and build user interfaces in .NET MAUI using both XAML and code-behind approaches. You'll learn how to use various layout containers, add UI controls, style them, and use Shell for page navigation.

📄 Understanding XAML and Code-Behind

XAML is a markup language used to define UI declaratively. Each XAML file has a corresponding C# file for event handling.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" x:Class="MyMauiApp.MainPage"> <VerticalStackLayout> <Label Text="Hello, XAML!" /> </VerticalStackLayout> </ContentPage>

📐 Working with Layouts

Layouts arrange controls visually. Common layouts:

  • StackLayout: Vertical or horizontal stack
  • Grid: Rows and columns
  • FlexLayout: Flexible, wrapping layout
<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Label Text="Header" Grid.Row="0" /> <Label Text="Content" Grid.Row="1" /> </Grid>

🎛️ Adding UI Elements

.NET MAUI provides a wide range of controls:

  • Label – displays text
  • Button – triggers actions
  • Entry – input field
  • Image – display images
<VerticalStackLayout> <Label Text="Username" /> <Entry Placeholder="Enter your name" /> <Button Text="Submit" Clicked="OnSubmitClicked" /> </VerticalStackLayout>

🎨 Styling with ResourceDictionary and Styles

You can define styles globally in App.xaml or locally on each page using <ResourceDictionary>.

<Application.Resources> <Style TargetType="Label"> <Setter Property="FontSize" Value="18" /> <Setter Property="TextColor" Value="DarkBlue" /> </Style> </Application.Resources>

🧭 Using Shell for Navigation

The Shell class simplifies navigation and structure. You define routes and navigation tabs easily in AppShell.xaml.

<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui" x:Class="MyMauiApp.AppShell"> <TabBar> <ShellContent Title="Home" ContentTemplate="{DataTemplate local:MainPage}" /> <ShellContent Title="Settings" ContentTemplate="{DataTemplate local:SettingsPage}" /> </TabBar> </Shell>

You can navigate using route names in code:

await Shell.Current.GoToAsync("//Settings");

🔚 Summary

You've learned the fundamentals of building UIs in .NET MAUI using XAML, layouts, and styles. You also explored Shell for efficient navigation. Mastering these elements allows you to create visually compelling and user-friendly apps.