Appendix B: Introduction to XAML

411

is that it is an XML document with elements, attributes, and namespaces. Each of the items you see has special meaning, as will be discussed in the following sections.

Elements as Classes

For XAML to be meaningful as code, elements must be associated with classes. The Window element in Listing B-1 is associated with a class named WpfApplication1

.MainWindow, specified by the x:Class attribute. The x prefix aliases the http://schemas

.microsoft.com/winfx/2006/xaml namespace, where the Class attribute is defined. By mapping the element to a class, you allow VS to compile the XAML into code that runs. Notice that the default namespace is http://schemas.microsoft.com/winfx/2006/xaml/ presentation, which defines how each of the elements without prefixes will be compiled to code. The important fact to realize here is that when writing XAML, you are creating a document that will be translated into executable code for you at compile time.

Attributes as Properties

Title, Height, and Width are attributes of the Window element in Listing B-1. When VS compiles the XAML, each of the attributes of elements will be translated to properties of the class that the element is translated to. More specifically, the WpfApplication1.

MainWindow class will have Title, Height, and Width properties. Each of the properties will be set with the value assigned to their corresponding attributes.

Executing the XAML Document

Remember that this is not a tutorial on WPF and that the focus needs to be on understanding how XAML works. Nevertheless, it’s informative to see what happens when XAML is compiled and executed. Press F5 or click the Start Debugging button on the toolbar to run this program. What you’ll see is a window similar to Figure B-1.

Figure B-1 shows how the Window element executed, creating an application window with normal title bar, minimize and close buttons, and borders. You can also see the results of applying the attributes of the Window element where MainWindow appears on the title bar and the dimensions are set by Height and Width.

This illustrates the power of XAML, where you can produce sophisticated results without writing a line of C# or VB code yourself. Of course, all of the XAML translates to code, but the declarative nature of XAML lets you say what you want without having to specify how it’s done. XAML saves you from writing a lot of code to produce equivalent results. The code that actually runs is generated for you.

Page 434
Image 434
Microsoft 9GD00001 manual Elements as Classes, Attributes as Properties, Executing the Xaml Document, 411