XAML Basics in .NET MAUI

Beginner 25 min read Lesson 3 of 8

What is XAML?

XAML (eXtensible Application Markup Language) is a declarative markup language used in .NET MAUI to define user interfaces. It separates UI design from code logic, making it easier to create and maintain applications.

Key Concept

XAML is XML-based, meaning it follows XML syntax rules and is both machine-readable and human-readable.

Basic XAML Structure

// MainPage.xaml


    
    
        

XAML Syntax

Elements and Attributes

// Element with attributes

XAML Namespaces

// Default namespace
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"

// XAML namespace
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

// Custom namespace
xmlns:local="clr-namespace:MyApp.Views"
xmlns:converters="clr-namespace:MyApp.Converters"

XAML Markup Extensions

// Binding

XAML vs Code-behind

// MainPage.xaml.cs
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        
        // Access XAML elements
        MyLabel.Text = "Hello from code-behind!";
    }
    
    private void OnButtonClicked(object sender, EventArgs e)
    {
        MyLabel.Text = "Button clicked!";
    }
}

// MainPage.xaml

    
        

Common XAML Controls

// Label

Complete Example

// MainPage.xaml


    
    
        
        
        
Key Takeaway
  • XAML provides a clean, declarative way to build UIs
  • Separation of UI and logic improves maintainability
  • XAML supports data binding and MVVM pattern
  • Code-behind complements XAML for event handling
Exercise

Create a XAML page with:

  1. Label with formatted text
  2. Entry for user input
  3. Button with click handler
  4. ListView or CollectionView
  5. Grid layout with multiple sections
Test Your Knowledge - Take Quiz