Categories
.NET .NET 8 .NET 9 .NET MAUI Android Blazor C# Desktop Developer Getting Started Hybrid iOS Mobile MVVM Windows XAML

XAML Basics: Building UI with .NET MAUI and More

Starting a new series entitled XAML for Beginners elucidates the concept of declarative markup to define UI in .NET applications. All articles within this series can be accessed from here.

The second installment of this series is now available to read here.

XAML is an acronym that stands for eXtensible Application Markup Language. It was first introduced in 2006, accompanying the initial release of Windows Presentation Foundation (WPF) alongside .NET 3.0.

The principal objective of this methodology is to segregate the UI design from the program logic. This separation allows the design team to focus solely on the UI, while the program logic can be developed and evaluated independently. Consequently, these components can be integrated into a unified system.

The MVVM design pattern is an exemplary framework for accomplishing this. However, XAML also supports the code-behind approach.

This markup language is founded upon constructs derived from XML. It allows developers to define UI elements, layout, and behavior in a clear, hierarchical structure.

Advantages:

  • Declarative Syntax
  • Separation of UI and Logic
  • Rich UI Design
  • Interoperability with C#

Disadvantages:

  • XAML cannot contain code (for .NET MAUI at least)
    • Employ the code-behind file for tasks such as event handling.
  • XAML cannot contain conditional code such as preprocessor directives.
  • XAML cannot contain loops for repetitive processing.
    • Employ UI elements such as BindableLayout and CollectionView, specifically tailored for such activities.
  • XAML elements necessitate a public, parameterless constructor for the UI element to function effectively.
    • This requirement can be circumvented in certain scenarios.
      • Examples will be provided in the Parameters article.

The series will cover the following:

XAML is compatible with various UI frameworks, including WPF, UWP, WinUI, and .NET MAUI (obviously Xamarin.Forms also). Software programming is constantly evolving, and so is XAML. Two specifications exist concerning XAML: one from 2006 and another from 2009.

Due to the nuanced differences among the various frameworks, this series will concentrate exclusively on .NET MAUI. And is based on the 2009 XAML spec.

Basics:

A fundamental understanding of XML is essential for comprehending XAML.

Building blocks of XAML:

  • Elements
    • Each element commences with a start tag and concludes with an end tag. It may also be self-closing.
    • <Grid></Grid>
    • <Label />
  • Attributes
    • Provide additional information about elements. Attributes are specified within the start tag of an element.
    • The value must be articulated within quotation marks.
    • Generally, they’re Properties/Events of the UI element.
    • <Button Text="Update" Clicked="OnClicked" />
  • Prolog
    • The declaration at the beginning of an XML document specifies the XML version and encoding used.
    • <?xml version="1.0" encoding="UTF-8" ?>
  • Processing Instruction
    • Provide directions to the XML parser. They are used to pass information to applications.
    • This must be cited before defining the root element and following the prologue.
    • <?xaml-comp compile="true" ?>
  • Namespaces
    • Provide a way to avoid element name conflicts by distinguishing elements and attributes defined by different XML schemas.
    • Defined with the special attribute named xmlns
    • <Grid xmlns="http://schemas.microsoft.com/dotnet/2021/maui" />
  • Comments
    • Notes or explanations within the XML code, which are ignored by the parser.
    • <!-- This is a comment -->
  • CDATA Sections
    • Used to include blocks of text that the XML parser should not parse.
    • CDATA sections are useful for including special characters or code.
    • In .NET MAUI, styles based on CSS are specified within this CDATA section.
    • <![CDATA[Content Here]]>
  • Entity References
    • Allow the inclusion of special characters and reusable content within XML.
    • The following symbols must always be encoded when utilized as content:
      • Less than (<)
        • &lt;
      • Greater than (>)
        • &gt;
      • Ampersand (&)
        • &amp;
      • Single quote (‘)
        • &apos;
      • Double quote (“)
        • &quot;
    • Apart from these, Unicode characters can be mentioned in the XAML file as follows:
      • &#<value>; – If the value is specified in decimal notation (in ASCII range). For example &#160;
      • &#x<value>; – If the value is specified in hex notation (with the x prefix). For example &#xF013; – Useful for specifying Font Glyphs

An XAML document must possess a singular, top-level root element; otherwise, it is rendered invalid.

<ContentPage
  xmlns="http://schemas.microsoft.com/dotnet/2021/maui">
  <!-- The root element -->
</ContentPage>

Namespaces:

All XML namespaces ought to be defined as attributes of the root element rather than being placed elsewhere within the document structure.

In the process of declaring an element or an attribute that is not part of the root namespace, the use of a prefix becomes essential. This prefix must align with an XML namespace that is defined at the root element.

In the example below, the Title serves as an attribute (property) of the ContentPage within the default namespace, while the Class is an attribute from a distinct namespace. So, a prefix is necessary for the Class attribute.

Here, the x:Class attribute delineates the fully qualified name of the UI element type, thereby enabling its reference in other segments of the application or externally, should it constitute a library (provided it is defined with the public scope).

<ContentPage
  x:Class="MyApp.Views.MainPage"
  xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  Title="Home">
  <!-- The root element -->
</ContentPage>

XML namespace can be defined in two ways:

  • URL-based
  • CLR namespace with Assembly name
<mct:Popup
  x:Class="MyApp.Views.MyPopup"
  xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:mct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
  <!-- Popup definition -->
</mct:Popup>

It is optional to include the assembly name when the references are contained within the same assembly.

<ContentPage
  x:Class="MyApp.Views.MainPage"
  xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:conv="clr-namespace:MyApp.Converters"  
  xmlns:vm="clr-namespace:MyApp.ViewModels;assembly=MyApp.Shared"
  x:DataType="vm:MainViewModel">
</ContentPage>

Content Property:

XAML offers the capability of the Content property. This allows for a more concise and readable syntax by omitting the explicit property tags. This attribute can be included once within the definition of the UI element type.

[ContentProperty(nameof(Children))]
public class Grid : Layout {}

Since the Children property is defined as a content property of the Grid, there is no necessity to include the Children tag when defining the Grid, as it is parsed implicitly.

Implicit Definition:

<ContentPage
  x:Class="MyApp.Views.MainPage"
  xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
  <Grid>  
    <Label
      Text="Hello .NET MAUI"
      HorizontalOptions="Center"
      VerticalOptions="Center" />
  </Grid>
</ContentPage>

Explicit Definition:

<ContentPage
  x:Class="MyApp.Views.MainPage"
  xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
  <Grid>  
    <Grid.Children>
      <Label
        Text="Hello .NET MAUI"
        HorizontalOptions="Center"
        VerticalOptions="Center" />
    </Grid.Children>
  </Grid>
</ContentPage>

I hope you now have a basic understanding of XAML. The subsequent article will cover Attached Properties, Generics, and Parameters.

Happy coding. Stay connected as we continue to learn and share the experiences from this exciting journey of being a .NET developer.

2 replies on “XAML Basics: Building UI with .NET MAUI and More”

Comments are closed.

Discover more from Developer Thoughts

Subscribe now to keep reading and get access to the full archive.

Continue reading