Basic structure of XAML elements
In this lesson, you will learn the basics of working with the XAML markup language.
XAML language basics
This markup language is used to create graphical interfaces in technologies such as .NET MAUI and WPF, and may look familiar to you if you have worked with HTML code or XML files, as the syntax is very similar.
If you want to declare an element in an XAML file, you must write the element name between a less than symbol and a greater than symbol:
Secondly, whenever we define an opening tag we must specify a way to close the element. There are two ways to do this, first, by declaring a closing tag:
It is also possible to add a diagonal at the end of the label to achieve the same goal:
You can practice by reviewing the labels of the project created by default. Next, I show you the syntax of the button, which follows the same structure that I have indicated above:
Properties of elements in a XAML file
Property Attributes
Another thing that is also important for you to know are the properties. Properties are the attributes or characteristics of each graphic element that you will be able to manipulate to make it look and behave as you need.
For example, if you wanted to modify the text that appears in the graphical interface of the previous button, you should modify the text property:
This way of assigning the value of properties within the same element definition is known as property attributes.
Elements of Property
The second way to assign values to properties is through property elements.
To assign a value in this way, we must work with an opening and a closing tag on the element we want to modify, and access the property as follows:
Difference between Property Attributes and Property Elements in XAML files
We might think that it is easier to assign values to a control through the property attributes, instead of creating the pair of tags for each property we would like to modify, which is true.
However, there are going to be times when the value we need to specify for a property is a complex value, as in the following example:
...
In the previous code, we can see a property called ItemTemplate of a control called CollectionView, to which we must assign an element type DataTemplate, which in turn contains a Layout type Grid. This is not possible to do it with Property Attributes directly.
Hierarchy in a XAML file
Finally, let's talk a little bit about the hierarchy of elements in a XAML file. Visual Studio does a great job of formatting the elements that are part of a XAML file, even showing us lines so that we can quickly identify the opening and closing tags, allowing us to see the hierarchy in the elements:
This tells us about a hierarchy between the elements in the XAML document. Once we know about the basic syntax of XAML files, we are ready to learn about .NET MAUI pages.