XAML (Extensible Application Markup Language)

XAML (Extensible Application Markup Language) is a markup language mainly used in developing applications on the .NET platform, especially in environments like WPF (Windows Presentation Foundation) y UWP (Universal Windows Platform). Allows you to design user interfaces in a declarative way, facilitating the separation between application logic and its visual presentation. XAML uses XML-like syntax, lo que lo hace accesible y fácil de entender. What's more, se integra bien con lenguajes de programación como C# y VB.NET, permitiendo a los desarrolladores crear aplicaciones ricas y dinámicas con mayor eficiencia.

Contents

XAML (Extensible Application Markup Language)

XAML (Extensible Application Markup Language) es un lenguaje de marcado desarrollado por Microsoft que se utiliza para la creación de interfaces de usuario en aplicaciones de Windows. Este lenguaje permite a los desarrolladores definir visualmente los elementos de la interfaz y sus interacciones, utilizando una sintaxis clara y estructurada. XAML es un componente crucial en el desarrollo de aplicaciones para plataformas como Windows Presentation Foundation (WPF), Universal Windows Platform (UWP) y Xamarin.Forms, facilitando la separación entre la lógica de la aplicación y la presentación visual.

Historia y Evolución de XAML

XAML fue introducido por primera vez en el contexto de Windows Presentation Foundation (WPF) con la llegada de .NET Framework 3.0 on 2006. Su objetivo principal era proporcionar una forma más intuitiva y declarativa de describir interfaces de usuario en comparación con la programación tradicional basada en código. Over time, XAML ha evolucionado, permitiendo la creación de aplicaciones más sofisticadas y modernas en diversas plataformas de Microsoft.

XAML en WPF

WPF es una de las primeras tecnologías que adoptó XAML como su principal lenguaje de diseño. WPF permite a los desarrolladores crear aplicaciones de escritorio con una rica interfaz gráfica y animaciones fluidas. XAML en WPF soporta controles de usuario, recursos, estilos y plantillas, lo que proporciona una experiencia de desarrollo robusta y flexible.

XAML in UWP

Con la introducción de Windows 10, XAML was adapted for use in Universal Windows Platform (UWP). UWP allows developers to create applications that work on all Windows devices, from PCs to tablets and phones. XAML in UWP introduces new controls and features that are responsible for modernizing the user interface, such as responsive design and touch support.

XAML in Xamarin.Forms

Xamarin.Forms is another platform that uses XAML for cross-platform mobile application development. Through XAML, developers can create user interfaces that adapt to different operating systems, like iOS and Android, using a common codebase. This allows considerable efficiency in mobile application development by reducing duplication of efforts.

XAML Structure

XAML is based on XML, which makes it readable and structured. The fundamental components of a XAML file structure are described below.

Elements and Attributes

In XAML, elements represent the user interface components, such as buttons, text boxes, and panels. Each element can contain attributes that define its properties. For example:

In this example, se define un botón con el texto "Clic aquí" and specific dimensions.

Namespaces

Namespaces in XAML are crucial to avoid conflicts between elements from different libraries. A XAML file can declare multiple namespaces to include elements from other libraries or namespaces:

In this example, The necessary namespaces are declared to use WPF elements.

Resources

Resources in XAML allow the definition of styles, templates and other reusable elements. This is especially useful to maintain consistency in the interface and facilitate global modification of styles. An example of a resource is the following:

This snippet defines a style for buttons that can be applied to multiple elements throughout the application.

Data Binding

One of the most powerful features of XAML is its ability to perform data binding, which allows the user interface and application logic to stay synchronized. Data binding in XAML can be done in various ways, including one-way and two-way binding.

One-Way Binding

One-way binding allows changes in the data source to be reflected in the user interface, but not the other way around. This type of binding is useful for displaying data that does not need to be edited by the user:

In this example, the TextBlock will show the value of the property Nombre from the data source.

Two-Way Binding

Two-way binding, on the other hand, allows changes in the user interface to be reflected in the data source, and vice versa. This is useful for input controls, such as text boxes:

With this binding, any change in the text box will update the property Nombre.

Styles and templates

Los estilos y plantillas en XAML permiten a los desarrolladores personalizar la apariencia de los controles y agregar comportamientos complejos a la interfaz.

Estilos

Los estilos definen un conjunto de propiedades para un control específico. Se pueden aplicar a controles individuales o a todos los controles de un tipo en particular. Al aplicar un estilo a un control, se pueden modificar múltiples propiedades de forma simultánea:

Templates

Las plantillas son más complejas que los estilos y permiten redefinir completamente la apariencia de un control. Las plantillas pueden incluir otros controles y definir su disposición y comportamiento:

In this example, se redefine completamente cómo se verá el botón, permitiendo un gran nivel de personalización.

Animaciones y Transiciones

XAML includes support for animations and transitions, which allows improving the user experience by adding visual effects to the interface. Animations can be defined directly in XAML and can be applied to element properties.

Animations

Animations in XAML are defined using the class Storyboard, which allows specifying which property will be animated, what values it will take and how long the animation will last:

In this example, when clicking the button, its opacity is reduced to 0 and then it reverts to its original state.

XAML and MVVM

The Model-View-ViewModel pattern (MVVM) is commonly used in XAML applications to separate business logic from the user interface. This approach facilitates testing and maintenance of complex applications.

Model

The model represents the data and business logic of the application. It contains the properties and methods necessary to operate with the data.

View

The view is the visual representation of the user interface, composed of XAML. It is responsible for displaying the data and interacting with the user.

ViewModel

The ViewModel acts as an intermediary between the model and the view, providing properties and commands that the view can bind to. It uses data binding to maintain the synchronization between the model and the user interface.

public class MiViewModel : INotifyPropertyChanged
{
    private string _nombre;
    public string Nombre
    {
        get { return _nombre; }
        set 
        { 
            _nombre = value; 
            OnPropertyChanged("Nombre"); 
        }
    }

    public ICommand ComandoEjemplo { get; set; }

    public MiViewModel()
    {
        ComandoEjemplo = new RelayCommand(EjecutarComando);
    }

    private void EjecutarComando()
    {
        // Lógica del comando
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

In this example, the ViewModel implements INotifyPropertyChanged to notify the view about changes in the properties.

Tools for XAML Development

There are various tools and development environments that facilitate the creation of applications using XAML. Microsoft Visual Studio is the most widely used tool and offers features such as IntelliSense, visual positioning of controls and a powerful debugger.

Visual Studio

Visual Studio provides a robust environment for XAML development. Its features include:

  • XAML Designer: Allows developers to drag and drop controls into the interface design and modify their properties visually.
  • IntelliSense: Offers contextual suggestions while writing XAML code, helping to prevent errors.
  • Purification tools: Allows developers to review and debug the application logic effectively.

Other Editors

In addition to Visual Studio, there are other editors that offer support for XAML, such as Expression Blend, which focuses on designing rich and animated user interfaces.

Conclusions

XAML se ha establecido como un lenguaje fundamental para el desarrollo de aplicaciones en el ecosistema de Microsoft. Su capacidad para separar la lógica de la presentación, junto con su integración con patrones de diseño como MVVM, lo convierte en una herramienta poderosa para crear aplicaciones modernas y ricas en interfaz de usuario. La evolución continua de XAML y su adopción en nuevas plataformas aseguran su relevancia en el futuro del desarrollo de software.

A medida que los desarrolladores se familiarizan cada vez más con las capacidades y características de XAML, se espera que continúe siendo una opción preferida para la creación de interfaces de usuario en el desarrollo de aplicaciones de Microsoft.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.