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:
- Root Element – Defines the page type (e.g.,
ContentPage, Shell).
- Namespaces – XML namespaces for XAML and custom controls.
- Resources – Styles, colors, templates defined in
<ContentPage.Resources> or globally.
- Layout – Containers like
Grid, StackLayout, VerticalStackLayout.
- Controls – UI elements like
Label, Entry, Button.
- Bindings – Data binding to ViewModel properties.
- 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.