Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 42 ยท XAML and Layouts

XAML Basics

Learn XAML for .NET MAUI - elements as objects, attributes as properties, property elements, content properties, event handlers, x:Name, namespaces, comments and how XAML relates to C#.

XAML (eXtensible Application Markup Language) is an XML dialect for creating objects and setting their properties. In MAUI you use it to describe screens: the pages, layouts and controls the user sees. The idea is simple: every XML element creates an object, and every attribute sets one of its properties. Anything you can do in XAML you can do in C#, but XAML is shorter, easier to read for layouts, and works with Hot Reload.

MAUI XAML is read-only on this site. The runnable stand-in is a tiny "XAML-like" loader written in C# that creates objects from XML with reflection. It shows the mechanism, not the MAUI parser.

Elements and attributes

This XAML and this C# build the same label (read-only):

XML
<Label Text="Hello" TextColor="Red" FontSize="20" />
C#
var label = new Label
{
    Text = "Hello",
    TextColor = Colors.Red,
    FontSize = 20
};

An element name is a class name (Label). An attribute is a property name (Text). The string "Red" is converted to a Color, and "20" to a double, by type converters. For non-text values such as enums, HorizontalOptions="Center" works the same way.

A page is a tree

A page contains one child, usually a layout, which contains controls:

XML
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="HelloApp.ProfilePage"
             Title="Profile">

    <VerticalStackLayout Padding="20" Spacing="10">
        <Label Text="Ada Lovelace" FontSize="28" />
        <Label Text="Mathematician" TextColor="Gray" />
        <Button Text="Follow" Clicked="OnFollowClicked" />
    </VerticalStackLayout>

</ContentPage>

Nesting means parent and child: the Labels and the Button are children of the VerticalStackLayout, which is the content of the ContentPage. There is no need to write <ContentPage.Content>, because Content is the page's content property: whatever you put between the tags goes there. Layouts have a Children content property in the same way.

Property element syntax

When a value is too complex for a string, write it as a child element named Type.Property:

XML
<Button Text="Save">
    <Button.Background>
        <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
            <GradientStop Color="Orange" Offset="0.0" />
            <GradientStop Color="Red" Offset="1.0" />
        </LinearGradientBrush>
    </Button.Background>
</Button>

Button.Background is a property element: the object inside becomes the value of the Background property. Use it whenever a property needs an object (brushes, shadows, templates, gestures).

Namespaces

The xmlns lines import namespaces:

  • xmlns="http://schemas.microsoft.com/dotnet/2021/maui" is the default namespace: all MAUI controls.
  • xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" gives x:Class, x:Name, x:Key, x:Type and other language features.
  • Your own namespaces: xmlns:local="clr-namespace:HelloApp.Models" lets you write <local:Person />. With assembly references: xmlns:vm="clr-namespace:HelloApp.ViewModels;assembly=HelloApp".

The namespaces and markup extensions lesson goes deeper.

x:Name and events

x:Name creates a field that code-behind can use. Event attributes hook a handler method with a matching signature:

XML
<Entry x:Name="NameEntry" Placeholder="Your name" TextChanged="OnNameChanged" />
<Button Text="Greet" Clicked="OnGreetClicked" />
C#
private void OnGreetClicked(object? sender, EventArgs e)
{
    DisplayAlertAsync("Hello", $"Hi {NameEntry.Text}!", "OK");
}

private void OnNameChanged(object? sender, TextChangedEventArgs e)
{
    // e.OldTextValue and e.NewTextValue
}

For larger apps, prefer binding and commands to event handlers (see MVVM), but handlers are fine for UI-only logic.

Attached properties

Some properties belong to a parent but are set on children. Grid.Row="1" is an attached property: the Grid defines it, and the child carries the value:

XML
<Grid RowDefinitions="Auto,*">
    <Label Grid.Row="0" Text="Header" />
    <Label Grid.Row="1" Text="Body" />
</Grid>

Other familiar ones: Grid.Column, Grid.RowSpan, AbsoluteLayout.LayoutBounds, FlexLayout.Grow, Shell.NavBarIsVisible.

Comments, escaping and whitespace

  • Comments use <!-- ... -->.
  • Write &amp;, &lt;, &gt; and &quot; for the characters &, <, > and " inside attribute text.
  • To keep leading or trailing spaces in text use xml:space="preserve".
  • For multi-line text in an attribute use &#10; for a line break, or use a property element with text content.
  • Braces start a markup extension ({Binding Name}). To show literal braces at the start of a string, escape them: Text="{}{literal}".

XAML is compiled

By default MAUI compiles XAML (XAMLC): the build turns the XAML into IL that creates objects directly. This gives faster start-up and catches errors such as misspelled property names at build time. Setting x:DataType on pages turns on compiled bindings too (see data binding basics).

A tiny XAML loader, runnable

The stand-in creates objects from XML by looking up classes by name and setting properties with reflection. Real XAML has type converters, content properties, namescopes and more, but the core idea is exactly this.

C# Stand-in: build objects from XML-like markup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you change Text to a misspelled Txt in the markup, the loader fails with a clear message. Real compiled XAML does the same at build time, which is a major benefit.

Common mistakes

  • Forgetting the x:Class or giving it a name that does not match the code-behind class.
  • Using a handler name that does not exist or has the wrong parameters (a build error).
  • Setting the same property both as an attribute and as a property element.
  • Putting two children directly in a ContentPage (it takes one; wrap them in a layout).
  • Using the wrong decimal format: write 1.5 (invariant culture) in XAML, regardless of device language.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In XAML, what does an attribute such as Text="Hi" represent?

    Elements create objects and attributes set their properties; converters turn strings into the property type.
  2. 2. Why can a ContentPage contain a layout without writing <ContentPage.Content>?

    A content property lets you put children directly between the tags; for ContentPage it is Content.
  3. 3. What is Grid.Row="1" on a child called?

    The Grid defines the property but the child carries the value, which is an attached property.
  4. 4. When is a misspelled property name in compiled XAML reported?

    XAML compilation checks property and type names at build time, so many errors are caught early.
  5. 5. How do you write a property value that is a complex object?

    Property element syntax nests an object element inside Type.Property.

Summary

  • XAML elements create objects; attributes set properties; nesting builds a tree.
  • Content properties, property elements and attached properties cover most syntax.
  • x:Name gives code-behind access; event attributes wire handlers.
  • XAML is compiled at build time, so many mistakes show up early.

Next: Stack and Grid Layouts