Property Elements
Rich composition of controls is one of the highlights of XAML. This can be easily demonstrated with a Button, because you can put arbitrary content inside it; you’re not limited to just text! To demonstrate this, the following code embeds a simple square to make a Stop button like what might be found in a media player:
Windows.UI.Xaml.Controls.Button
b =new
Windows.UI.Xaml.Controls.Button
(); b.Width = 96; b.Height = 38; Windows.UI.Xaml.Shapes.Rectangle
r =new
Windows.UI.Xaml.Shapes.Rectangle
(); r.Width = 10; r.Height = 10; r.Fill =new
Windows.UI.Xaml.Media.SolidColorBrush
(Windows.UI.Colors
.White); b.Content = r;// Make the square the content of the Button
Button’s Content property is of type System.Object, so it can easily be set to the 10x10 Rectangle object. The result (when used with additional code that adds it to a page) is pictured in Figure 2.1.
Figure 2.1. Placing complex content inside a Button
That’s pretty neat, but how can you do the same thing in XAML with property attribute syntax? What kind of string could you possibly set Content to that is equivalent to the preceding Rectangle declared in C#? There is no such string, but XAML fortunately provides an alternative (and more verbose) syntax for setting complex property values: property elements. It looks like the following:
<
Button
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Width
="96"
Height
="38">
<
Button.Content
>
<
Rectangle
Width
="10"
Height
="10"
Fill
="White"/>
</
Button.Content
>
</
Button
>
The Content property is now set with an XML element instead of an XML attribute, making it equivalent to the previous C# code. The period in Button.Content is what distinguishes property elements from object elements. Property elements always take the form TypeName.PropertyName, they are always contained inside a TypeName object element, and they can never have attributes of their own (with one exception—the x:Uid attribute used for localization).
Property element syntax can be used for simple property values as well. The following Button that sets two properties with attributes (Content and Background):
<
Button
xmlns
=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation
"Content
=
"Stop
"Background
=
"Red
"/>
is equivalent to this Button, which sets the same two properties with elements:
<
Button
xmlns
=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation
">
<
Button.Content
>
Stop</
Button.Content
>
<
Button.Background
>
Red</
Button.Background
>
</
Button
>
Of course, using attributes when you can is a nice shortcut when hand-typing XAML.