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
// Nested elements
// Property element syntax
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
// Static Resource
// Dynamic Resource
// Binding with Path
// Binding with Converter
// Multibinding
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
// Button
// Entry
// Image
// ListView
Complete Example
// MainPage.xaml
// MainPage.xaml.cs
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainPageViewModel();
}
}
public class MainPageViewModel
{
public string Name { get; set; }
public ICommand GreetCommand { get; }
public MainPageViewModel()
{
GreetCommand = new RelayCommand(Greet);
}
private void Greet()
{
// Implementation
}
}
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:
- Label with formatted text
- Entry for user input
- Button with click handler
- ListView or CollectionView
- Grid layout with multiple sections