XAML Concepts in .NET MAUI

Extensible Application Markup Language (XAML) is an XML-based language used by .NET MAUI to define user interfaces. XAML allows you to separate the UI design from the application logic, making your code more organized and maintainable.

Key Takeaway: XAML provides a declarative way to build UIs, which can be more intuitive and efficient than writing UI code directly in C#.

What is XAML?

XAML is an XML dialect specifically designed for creating user interfaces. In .NET MAUI, XAML is used to define the structure, layout, and appearance of your application's screens. Instead of programmatically creating UI elements, you describe them in a XAML file.

Here's a simple example of a XAML file defining a button:


<Button Text="Click Me"
        HorizontalOptions="Center"
        VerticalOptions="CenterAndExpand" />
            

Key XAML Elements and Concepts

Elements and Attributes

In XAML, UI elements are represented by XML tags, and their properties are defined by attributes. For example, the Button element has attributes like Text, HorizontalOptions, and VerticalOptions.

Layouts

.NET MAUI provides several layout containers to arrange your UI elements:

Example of a StackLayout:


<StackLayout Orientation="Vertical">
    <Label Text="First Item" />
    <Label Text="Second Item" />
</StackLayout>
            

Data Binding

Data binding is a powerful feature that allows you to create a connection between your UI elements and your application's data. Changes in the data automatically reflect in the UI, and vice-versa.

Example of data binding:


<Label Text="{Binding WelcomeMessage}" />
            

Control Templates

Control templates allow you to redefine the visual structure of a control without changing its behavior. This is useful for creating custom-styled controls.

Resources

XAML supports a ResourceDictionary where you can define reusable styles, templates, and other objects that can be applied to multiple elements across your application.


<ContentPage.Resources>
    <Style TargetType="Button">
        <Setter Property="BackgroundColor" Value="CornflowerBlue" />
        <Setter Property="TextColor" Value="White" />
    </Style>
</ContentPage.Resources>
            

XAML Compilation

.NET MAUI XAML is compiled at build time into .NET Intermediate Language (IL), which is then processed by the XAML compiler. This improves performance and catches XAML errors early in the development cycle.

XAML vs. C# for UI

While you can create UIs entirely in C#, XAML offers:

Best Practice: Use XAML for defining your UI structure and appearance, and use C# for implementing application logic, event handling, and data manipulation.

Next Steps

Explore different layout containers, practice data binding, and experiment with styles to master XAML in .NET MAUI.