Previous AppShell-vs-MainPage MAUI-Application-Tag Next

App.xaml vs AppShell.xaml vs MainPage.xaml in .NET MAUI

Anatomy of a XAML File in .NET MAUI

XAML (Extensible Application Markup Language) is used to define the UI in .NET MAUI applications. It separates the UI design from the logic, making the code cleaner and easier to maintain.

Basic Structure of a XAML File

A typical XAML file consists of:

  1. Root Element – Defines the page type (e.g., ContentPage, Shell).
  2. Namespaces – XML namespaces for XAML and custom controls.
  3. Resources – Styles, colors, templates defined in <ContentPage.Resources> or globally.
  4. Layout – Containers like Grid, StackLayout, VerticalStackLayout.
  5. Controls – UI elements like Label, Entry, Button.
  6. Bindings – Data binding to ViewModel properties.
  7. Behaviors & Triggers – Add dynamic functionality.

Flow Diagram

XAML File
 ├── Root Element (e.g., ContentPage)
 │    ├── XML Namespaces
 │    ├── Resources (Styles, Templates)
 │    └── Layout Container
 │         ├── Controls
 │         │    ├── Properties
 │         │    ├── Bindings
 │         │    └── Behaviors / Triggers
    

Example XAML File

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MyApp"
             x:Class="MyApp.MainPage">

    <ContentPage.Resources>
        <Style TargetType="Label">
            <Setter Property="TextColor" Value="Blue" />
        </Style>
    </ContentPage.Resources>

    <VerticalStackLayout Padding="20">
        <Label Text="Welcome to .NET MAUI!" FontSize="24" />
        <Entry Placeholder="Enter your name" />
        <Button Text="Submit" Command="{Binding SubmitCommand}" />
    </VerticalStackLayout>

</ContentPage>
    

Key Points

  • 💡 Use Resources for reusable styles.
  • 💡 Keep layout simple and responsive using Grid or StackLayout.
  • 💡 Bind controls to ViewModel properties for MVVM compliance.
  • 💡 Add behaviors for validation and triggers for animations.
Back to Index
Previous AppShell-vs-MainPage MAUI-Application-Tag Next
*