UWP Development, Understanding the XAML Language for Screen Development

The Universal Windows Platform (UWP) is a platform created by Microsoft that allows developers to create applications that run on Windows 10 and later operating systems. UWP applications focus on providing a common user experience across various devices. Among them, XAML (Extensible Application Markup Language) is an essential language used to define the UI of UWP applications. In this article, we will explore the basic concepts and features of XAML and how it can be utilized to implement screens in UWP applications.

Basic Concepts of XAML

XAML is an XML-based markup language used to declaratively define UI elements and properties. By using XAML, developers can intuitively design the UI and write UI-related logic in languages such as C# or VB.NET behind the code. This structure facilitates collaboration between developers and designers, allowing for effective role division.

Basic Syntax of XAML

The basic structure of XAML is as follows:

<Page x:Class="YourApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:YourApp">
    <Grid>
        <TextBlock Text="Hello, World!" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</Page>

In the code above, the main elements are as follows:

  • Page: The root element of the XAML document, representing the page.
  • x:Class: Specifies the name of the code-behind class associated with the current XAML file.
  • xmlns: Defines the XML namespace to differentiate elements and properties that can be used in XAML.
  • Grid: A layout container for placing UI elements.
  • TextBlock: A UI element that displays text, which can enhance user experience through various properties.

Properties and Events

In XAML, UI elements define their styles and behaviors through attributes. Typically, XAML properties are assigned in dot notation, for example, to change the text of a TextBlock, you would write:

<TextBlock Text="Hello, World!" Foreground="Blue" FontSize="24" />

Additionally, XAML supports event handling. For instance, to define an action to be performed when a button is clicked, you could write:

<Button Content="Click Me!" Click="Button_Click" />

The above code creates a button labeled “Click Me!” that calls the event handler Button_Click when clicked.

Layouts and Widgets in XAML

XAML provides various layout containers to facilitate the arrangement of UI elements. The most common layout containers include Grid, StackPanel, WrapPanel, RelativePanel, and Canvas.

Grid

Grid is the most flexible and powerful layout container. It can define rows and columns to implement complex layouts. Here’s a simple example using Grid:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Grid.Row="0" Grid.Column="0" Text="Header" />
    <Button Grid.Row="1" Grid.Column="0" Content="Button 1" />
    <Button Grid.Row="1" Grid.Column="1" Content="Button 2" />
</Grid>

In the example above, the Grid consists of two rows and two columns. The first row is set to dynamic size, and the second row contains two buttons.

StackPanel

StackPanel is a layout container that stacks child elements horizontally or vertically. It is typically useful for listing simple items. A vertical stack example:

<StackPanel Orientation="Vertical">
    <TextBlock Text="Item 1" />
    <TextBlock Text="Item 2" />
    <Button Content="Click Me!" />
</StackPanel>

Other Layouts

WrapPanel is a panel that automatically wraps child elements to the next line, while RelativePanel allows for setting relative positions between UI elements. Each layout container can be chosen according to specific UI requirements.

Data Binding and MVVM Pattern

Another important feature of XAML is data binding. Data binding allows you to establish connections between UI elements and data sources, enabling the UI to change dynamically based on the data. The MVVM (Model-View-ViewModel) pattern can be utilized to manage data effectively.

Simple Data Binding Example

Here’s an example of simple data binding in XAML:

<Page x:Class="YourApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Page.DataContext>
        <local:MyViewModel />
    </Page.DataContext>

    <StackPanel>
        <TextBlock Text="{Binding Title}" FontSize="32" />
        <Button Content="Update Title" Command="{Binding UpdateTitleCommand}" />
    </StackPanel>
</Page>

In the above code, the MyViewModel class is set as the data context, and the Text property of the TextBlock is bound to the Title property of that data context.

ViewModel Example

A ViewModel class can be written as follows:

public class MyViewModel : INotifyPropertyChanged
{
    private string _title = "Initial Title";
    public string Title
    {
        get => _title;
        set
        {
            if (_title != value)
            {
                _title = value;
                OnPropertyChanged(nameof(Title));
            }
        }
    }

    public ICommand UpdateTitleCommand { get; }

    public MyViewModel()
    {
        UpdateTitleCommand = new RelayCommand(UpdateTitle);
    }

    private void UpdateTitle()
    {
        Title = "The title has been updated!";
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Styles and Templates

XAML uses styles and templates to maintain a consistent format for UI elements. This helps reduce code duplication and makes UI-based applications more appealing.

Style Example

You can define common properties for TextBlock using styles:

<Page.Resources>
    <Style x:Key="MyTextBlockStyle" TargetType="TextBlock">
        <Setter Property="FontSize" Value="24" />
        <Setter Property="Foreground" Value="Green" />
    </Style>
</Page.Resources>

<TextBlock Style="{StaticResource MyTextBlockStyle}" Text="Text with applied style" />

Styles are very helpful in consistently applying visual properties to UI elements.

Templates

Templates are used to redefine the visual structure of UI elements. Here’s an example of changing the default style of a Button:

<Style TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Background="{TemplateBinding Background}" Padding="10">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Border>
            </ControlTemplate>
        <Setter.Value>
    </Setter>
</Style>

Animations and Transitions

XAML allows for easy application of animations and transitions to enhance the user experience. This makes the interactions in applications feel more appealing and intuitive.

Animation Example

Here’s an example of a simple animation that changes size:

<Button Content="Animation Button" Width="100" Height="100">
    <Button.RenderTransform>
        <ScaleTransform x:Name="buttonScale" />
    </Button.RenderTransform>
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.PointerEntered">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="buttonScale" Storyboard.TargetProperty="ScaleX" To="1.2" Duration="0:0:0.2"/>
                    <DoubleAnimation Storyboard.TargetName="buttonScale" Storyboard.TargetProperty="ScaleY" To="1.2" Duration="0:0:0.2"/>
                </Storyboard>
            <BeginStoryboard>
        </EventTrigger>
        <EventTrigger RoutedEvent="Button.PointerExited">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="buttonScale" Storyboard.TargetProperty="ScaleX" To="1.0" Duration="0:0:0.2"/>
                    <DoubleAnimation Storyboard.TargetName="buttonScale" Storyboard.TargetProperty="ScaleY" To="1.0" Duration="0:0:0.2"/>
                </Storyboard>
            <BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
</Button>

The above code sets the button to grow in size when the mouse hovers over it, and return to its original size when the mouse leaves.

Conclusion

XAML is a very powerful tool for defining and manipulating UI elements in UWP applications. With features like data binding, styles, and animations, developers can provide a consistent user experience and implement greater flexibility regarding UI characteristics. Understanding XAML is essential when starting UWP development, and it is necessary to gradually learn its use through practice. I hope this article helps enhance your understanding of UWP development and the XAML language.

We will continue to cover various topics related to UWP development, so stay tuned. If you have any questions, please leave a comment!

© 2023 UWP Development Course Blog