XAML Marks the Spot

How to use XAML in a Silverlight application

Download the code for this article here.

XML-based languages have been on the rise since XML was released in 1998. Extensible Stylesheet Language Transformations (XSLT), Scalable Vector Graphics (SVG), and even XHTML have roots that tie back to XML. By using an XML-based language, the visual portion of an application can be created with a more friendly syntax without having to resort to programming languages such as C#, Visual Basic, or even JavaScript. This has many potential benefits, including the ability to more easily separate designer and programmer tasks, simplify maintenance, and provide a more flexible base for writing development tools such as Microsoft s Expression Blend 2 product.

Windows Presentation Foundation (WPF) and Silverlight are prime examples of frameworks that rely on an XML-based, declarative language to define the visual parts of an application. Both use Extensible Application Markup Language (XAML) to declare different shapes, transformations, and controls, which allows designers to get involved in the application development process more easily. Developers then can step in and add code to retrieve data, perform business rules, and perform other logic. Although Silverlight supports a subset of the overall WPF XAML language, it's key for developers just getting into Silverlight development to learn how XAML works and how it can be used in an application.

In this article I'll walk you through some key aspects of XAML, and describe how you can use it to define shapes, layout controls, and user input controls. If you've worked with HTML or other XML-based languages, you'll pick up XAML quickly. If you haven't, there will certainly be a learning curve but the curve is minimal once you understand the rules that come into play. Regardless of your experience working with XML-based languages, learning XAML is essential to building Silverlight applications, so let s get started by taking a quick look at some of the rules.

XAML Rules
HTML provides a way to define visual aspects of a web application using elements and attributes. Although early forms of HTML weren't very strict, the latest version of XHTML is more in line with the rules originally defined in the XML 1.0 specification. Because XAML is an XML-based language, it is subject to the same rules and requires the rules to be followed in order for your Silverlight applications to run. Here are a few XAML rules to know about up front:

•    Case matters
•    All starting elements (tags) must have corresponding closing tags
•    Attributes must be quoted

As an example, let s assume you d like to define some text in a Silverlight application. XAML provides a TextBlock element that can be used to perform that particular task; it is much like a span tag in HTML:

<TextBlock x:Name="FirstName"
Text="First Name:"></TextBlock>

This portion of XAML code is well formed (meaning that it follows the XML rules). The starting element has a corresponding closing element, the attributes (x:Name and Text) have quoted values, and the case of the tags matches perfectly. A shortcut version of the TextBlock tag can also be defined in cases where no content is added between the start and end tags (as with the previous example):

<TextBlock x:Name="FirstName" Text="First Name:" />

Defining Shapes Using XAML
Silverlight provides the flexibility to define different types of shapes that would be difficult to do in HTML without resorting to images. Shapes such as rectangles, circles, and lines are all defined using XAML, and can be created using the Visual Studio 2008 SP1 editor or Expression Blend 2 SP1. Figure 1 shows how a rectangle and ellipse can be defined using XAML syntax. Figure 2 shows what the XAML renders when the Silverlight application is run.

Figure 1: Defining shapes using XAML syntax

<Canvas Height="300" Width="300">
<Rectangle Height="7" Width="300" Stroke="#000000"
Canvas.Top="81" Canvas.Left="75">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0.555,0.627"
EndPoint="1.024,0.597">
<GradientStop Color="#FF000000" Offset="0.228"/>
<GradientStop Color="#FFFFFFFF" Offset="0.839"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Ellipse Height="104" Width="129" Stroke="#000000"
Fill="Blue" StrokeThickness="2"/>
<TextBlock Height="41" Width="106" Canvas.Top="26" Canvas.Left="11"
FontStyle="Italic" FontWeight="Normal" FontSize="36" Text="ACME"
Foreground="#FFFFFF" />
<TextBlock Height="46" FontStyle="Italic" Canvas.Top="28"
Canvas.Left="134" FontSize="36" Text="Corporation" />
</Canvas>


Figure 2: Output of the XAML shown in Figure 1 when rendered in Silverlight

Looking through Figure 1 you'll see that the XAML elements and attributes are quite straightforward and somewhat similar to what you may have seen in HTML. You can define the height and width of shapes, define fill colors, stroke (border) colors, and thicknesses, plus more. Notice that the Rectangle element doesn't have a Fill attribute defined on it. Instead, the fill is a linear gradient (as opposed to a radial gradient, which is used in ellipses) that is defined inside the element named Rectangle.Fill.



Gradients can have start and end points defined, as well as the colors for the gradient. This example uses the GradientStop element to define two colors for the gradient (black and white), as well as where the colors should start on a scale of 0 to 1 (using the Offset attribute). Creating the XAML for gradients can be a bit tedious when done by hand, which is why Microsoft has released tools like Expression Blend 2 that allow XAML to be defined visually. I'll introduce and explore Expression Blend 2 in future articles.

All the shapes and text shown in Figure 1 are placed within an XAML container control named Canvas and arranged within it. Canvas is an absolute positioning type of layout control, which is useful when different parts of an application need to be arranged precisely. Looking at the attributes defined on each of the shapes in Figure 1 you'll see Canvas.Top and Canvas.Left attributes defined. These attached property attributes are used to position the element relative to the parent Canvas container, with 0,0 being the upper-left part of the Canvas. They re referred to as attached properties because they re attaching to the overall layout of the parent Canvas element. If the Canvas element is moved somewhere else in the application, the children of Canvas will still be positioned properly within it.

In addition to the Canvas control, Silverlight provides several other types of layout controls that provide more flexible layout options, such as StackPanel and Grid. I'll discuss these controls in an upcoming article, and provide additional details about how to use them.

Interacting with XAML
Although it's convenient to be able to define shapes and text using XAML, applications need to be able to interact with XAML programmatically to perform a variety of operations. For example, when a user moves their mouse over an ellipse, you may want to change the fill color or perform some other type of task. Interacting with XAML is fairly straightforward in Silverlight, and in many ways is a lot like interacting with ASP.NET server controls using JavaScript, C#, or Visual Basic. You can handle click events, mouse enter and leave events, plus much more.

To change the fill color of an ellipse as a user moves their mouse over it you can add MouseEnter and MouseLeave event definitions on the Ellipse tag in the XAML file, and define C# or Visual Basic event handlers to handle the events. Here s an example of defining MouseEnter and MouseLeave event handlers in XAML on an Ellipse named MyEllipse:

<Ellipse x:Name="MyEllipse"
MouseEnter="MyEllipse_MouseEnter"
MouseLeave="MyEllipse_MouseLeave"
Height="104" Width="129" Stroke="#000000"
Fill="Blue" StrokeThickness="2"/>

Figure 3 shows C# code to handle the MouseEnter and MouseLeave events to change the fill color of the ellipse. The code accesses the Ellipse control by name, then creates a SolidColorBrush and associated color, which is assigned to the Fill property.

Figure 3: Handling events and interacting with XAML


private void MyEllipse_MouseEnter(object sender, MouseEventArgs e)
\\{
MyEllipse.Fill = new SolidColorBrush(Colors.Red);
\\}
private void MyEllipse_MouseLeave(object sender, MouseEventArgs e)
\\{
MyEllipse.Fill = new SolidColorBrush(Colors.Blue);
\\}

You also can handle the standard Click event on controls such as Button. Figure 4 shows an example of defining TextBox and Button controls in XAML and defining an event handler to call when the Button control is clicked.

Figure 4: Defining a Click event handler on a Button control in XAML

<TextBox x:Name="FirstName" Height="20" Width="200" />
<Button x:Name="SubmitButton" Height="20" Width="100"
Click="SubmitButton_Click" Content="Click Me!" />


Figure 5 shows a Click event handler named SubmitButton_Click that is used to display the text entered into the TextBox control using a MessageBox.

Figure 5: Handling a Button control's Click event

private void SubmitButton_Click(object sender, RoutedEventArgs e)
\\{
MessageBox.Show("Clicked the button");
\\}

Looking through the code in Figures 4 and 5, you'll see that it's much like working with standard ASP.NET controls and their associated event handlers. Silverlight shapes and controls are defined in XAML much like ASP.NET controls are defined in an aspx page. Event handlers are defined in a code-beside file and can interact with the different controls.

Conclusion
In this article you've been introduced to the fundamentals of XAML and learned some of the rules that apply to it. Silverlight is quite picky when it comes to following the rules, so you'll need to be careful to case your tags consistently, close your tags, and quote your attributes.

Many different types of objects can be defined using XAML, ranging from layout controls such as Canvas, shapes and text controls, and even user input controls. In the next article we'll continue our discussion of XAML and jump into the world of layout controls. I'll provide examples of using Canvas, Grid, StackPanel, and Border controls.


Dan Wahlin, a Microsoft MVP for ASP.NET and XML Web services, founded the XML for ASP.NET Developers website and The Wahlin Group (www.TheWahlinGroup.com), which specializes in .NET, Silverlight, and SharePoint consulting and training solutions.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish