Exploring the XAML Element Tree in WPF
Free Excerpt from Chapter 2 of the book WPF 4.0 In Simple Steps by Kogent Learning Solutions Inc.
As you know, you can create both standalone applications and XBAPs with the help of WPF. When you create a WPF application in Visual Studio 2010, the default XAML code provides
the default UI of the application. The XAML code is a hierarchy of several XAML elements, which are markup entities that indicate some information about the UI controls. The default XAML code of a WPF application contains two XAML elements— Window and Grid for standalone applications and Page and Grid for XBAPs. The Window element and the Page element are the root elements in standalone applications and XBAPs, respectively. There can be exactly one root element in the XAML code of a WPF application. In addition, the root element, the WPF application can have exactly one child element. By default, the Grid element is the child element of the Window and Page elements in the standalone applications and XBAPs, respectively.
However, in WPF standalone and XBAP applications you can have other child elements by adding controls in the parent elements. When you add controls to a WPF application at design time, each control corresponds to an XAML element. These elements become the child elements of the default Grid element. Depending on the type of the element, these child elements can in turn contain other child elements. For example-The Button control is a child element of the Grid control, which in turn can have Label as a child element. In this way, the entire UI of a WPF application takes the form of a tree-like structure.
In this tree, there is one root node with only one child node. The child node in turn has one or more child nodes. The tree branches out to show the UI of the application as you keep adding controls or XAML elements in a WPF application.
Let’s take an example of a WPF standalone application named MyWPFApplication, which is created using Visual C#. Listing 2.1 shows the XAML code of the application:
Listing 2.1: Showing the XAML Code of the MyWPFApplication Application
<Window x:Class=”MyWPFApplication.MainWindow
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Title=”MainWindow” Height=”300″ Width=”300″>
<Grid>
<Button Margin=”100,25,100,200″ Name=”button1″>Welcome</Button>
<Button Margin=”100,100,100,125″ Name=”button2″>WPF</Button>
<Button Margin=”50,150,50,10″ Name=”button3″>
<Label Margin=”5,5,5,5″ Name=”label1″>XAML</Label>
</Button>
</Grid>
</Window>
In Listing 2.1, there are four XAML elements, namely Window, Grid, Button, and Label. The Window and Grid elements exist in the WPF application by default, while the Button and Label elements are added by dragging and dropping the Button and Label controls from the Toolbox.
Comments