MSDN Community

XAML Basics

XAML (Extensible Application Markup Language) is a declarative, XML-based language used to define user interfaces and other parts of an application. It's a core technology in Windows Presentation Foundation (WPF), Universal Windows Platform (UWP), and .NET MAUI.

What is XAML?

XAML allows you to separate the presentation layer (UI) from the application logic. This separation makes it easier for designers and developers to collaborate and for the UI to be maintained and updated independently.

Key Concepts

Here are some fundamental concepts to understand when working with XAML:

Elements and Attributes

XAML is structured around elements (which typically map to classes in your .NET code) and attributes (which map to properties of those classes).

<!-- A simple Button element with Text and Click event attributes -->
<Button Content="Click Me" Click="OnButtonClick" />

Properties and Data Binding

XAML is used to set properties of UI elements. Data binding is a powerful mechanism that allows UI elements to be updated automatically when the underlying data changes.

<!-- Binding the Text property of a TextBlock to a data source -->
<TextBlock Text="{Binding UserName}" />

Layout

XAML provides various layout panels like Grid, StackPanel, and Canvas to arrange UI elements on the screen.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Header" Grid.Row="0" />
    <ContentPresenter Content="{Binding MainContent}" Grid.Row="1" />
</Grid>

Resources

XAML supports defining reusable resources like styles, templates, and brushes, which can be applied to multiple elements.

<!-- Defining a style for buttons -->
<Page.Resources>
    <Style TargetType="Button">
        <Setter Property="Background" Value="Blue" />
        <Setter Property="Foreground" Value="White" />
    </Style>
</Page.Resources>

<Button Content="Styled Button" />

Control Templates

Control templates allow you to customize the visual appearance of standard controls without changing their behavior.

Common XAML Controls

Next Steps

Explore more advanced topics like: