MSDN Community

Understanding XAML: An Overview

XAML (eXtensible Application Markup Language) is a declarative markup language that allows you to create user interfaces for Windows applications. It's a powerful tool for defining the structure, layout, and appearance of your application's UI, separating it from the application's logic.

What is XAML?

XAML is an XML-based language. This means it uses tags and attributes to define elements and their properties. In the context of Windows development, XAML is most commonly used with technologies like:

The primary benefit of XAML is the clear separation of concerns. Designers can focus on the UI using XAML, while developers can concentrate on the application's behavior and logic in C# or VB.NET.

Core Concepts of XAML

Elements and Properties

XAML constructs are built using elements, which represent UI objects, and properties, which define their characteristics. Every XAML element typically maps to a class in the .NET framework.

For example, a basic Button element might look like this:


<Button Content="Click Me"
        HorizontalAlignment="Center"
        VerticalAlignment="Center" />
        

In this example:

Layout and Panels

XAML uses layout panels to arrange child elements within a container. Common panels include:

Here's an example using a Grid:


<Grid>
    <RowDefinition />
    <RowDefinition />

    <Button Grid.Row="0" Content="Button 1" />
    <Button Grid.Row="1" Content="Button 2" />
</Grid>
        

Data Binding

One of XAML's most powerful features is data binding. It allows you to connect UI elements to data sources dynamically. When the data changes, the UI updates automatically, and vice versa.

Example of binding a TextBlock's text to a property named MyText:


<TextBlock Text="{Binding MyText}" />
        

Event Handling

XAML can also define event handlers. When an event occurs (e.g., a button click), the specified method in your code-behind file is executed.

Example of handling a button's Click event:


<Button Content="Click Me" Click="MyButton_Click" />
        

And in your C# code-behind (MyButton_Click.cs):


public void MyButton_Click(object sender, RoutedEventArgs e)
{
    // Handle the click event here
    MessageBox.Show("Button clicked!");
}
        

Advantages of Using XAML

Getting Started

When you create a new WPF or UWP project in Visual Studio, you'll typically find a default MainWindow.xaml or App.xaml file that contains the basic structure of your application's UI. You can start by modifying these files to build your interface.

For further details and advanced topics, please refer to the official Microsoft documentation on WPF and UWP XAML.