Elements and Attributes
The XAML specification defines rules that map .NET namespaces, types, properties, and
events into XML namespaces, elements, and attributes. You can see this by examining the
following simple (but complete) XAML file that declares a WPF Button and comparing it
to the equivalent C# code:
XAML:
<Button xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
Content=”OK” />
C#:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
b.Content = “OK”;
Although these two snippets are equivalent, you can instantly view the XAML in Internet Explorer and see a live button fill the browser window, as pictured in Figure 2.1, whereas the C# code must be compiled with additional code to be usable. Declaring an XML element in XAML (known as an object element) is equivalent to instantiating the corresponding .NET object via a default constructor. Setting an attribute on the object element is equivalent to setting a property of the same name (called a property attribute) or hooking up an event handler of the same name (called an event attribute). For example, here’s an update to the Button that not only sets its Content property but also attaches an event handler to its Click event:
XAML:
<Button xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
Content=”OK” Click=”button_Click”/>
C#:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
b.Click += new System.Windows.RoutedEventHandler(button_Click);
b.Content = “OK”;
This requires a method called button_Click to be defined somewhere, with the appropriate signature, which means that the XAML file can no longer be rendered standalon.
Enjoy!!