June 15, 2009 12:06 AM

XAML Marks the Spot

How to Use XAML in a Silverlight Application
DevConnections
Rating: (0)

Silverlight 101

XAML Marks the Spot

How to Use XAML in a Silverlight Application

By Dan Wahlin

XML-based languages have been on the rise since XMLwas 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 becreated with a more friendly syntax without having to resort to programminglanguages such as C#, Visual Basic, or even JavaScript. This has many potentialbenefits, including the ability to more easily separate designer and programmertasks, simplify maintenance, and provide a more flexible base for writingdevelopment tools such as Microsoft s Expression Blend 2 product.

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

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

XAML Rules

HTML provides a way to define visual aspects of aweb application using elements and attributes. Although early forms of HTMLweren t very strict, the latest version of XHTML is more in line with the rulesoriginally defined in the XML 1.0 specification. Because XAML is an XML-basedlanguage, it is subject to the same rules and requires the rules to be followedin order for your Silverlight applications to run. Here are a few XAML rules toknow about up front:

        Case matters

        All starting elements (tags) must have correspondingclosing tags

        Attributes must be quoted

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

<TextBlock x:Name="FirstName"

Text="FirstName:"></TextBlock>

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

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

Defining Shapes Using XAML

Silverlight provides the flexibility to definedifferent types of shapes that would be difficult to do in HTML withoutresorting to images. Shapes such as rectangles, circles, and lines are alldefined using XAML, and can be created using the Visual Studio 2008 SP1 editoror Expression Blend 2 SP1. Figure 1 shows how a rectangle and ellipse can bedefined using XAML syntax. Figure 2 shows what the XAML renders when theSilverlight application is run.

<Canvas Height="300" Width="300">

<RectangleHeight="7" Width="300" Stroke="#000000"

Canvas.Top="81"Canvas.Left="75">

<Rectangle.Fill>

<LinearGradientBrushStartPoint="0.555,0.627"

EndPoint="1.024,0.597">

<GradientStopColor="#FF000000" Offset="0.228"/>

<GradientStopColor="#FFFFFFFF" Offset="0.839"/>

</LinearGradientBrush>

</Rectangle.Fill>

</Rectangle>

<EllipseHeight="104" Width="129" Stroke="#000000"

Fill="Blue"StrokeThickness="2"/>

<TextBlockHeight="41" Width="106" Canvas.Top="26"Canvas.Left="11"

FontStyle="Italic"FontWeight="Normal" FontSize="36"Text="ACME"

Foreground="#FFFFFF" />

<TextBlockHeight="46" FontStyle="Italic" Canvas.Top="28"

Canvas.Left="134"FontSize="36" Text="Corporation" />

</Canvas>

Figure 1: Defining shapes using XAML syntax

Figure 1

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

Looking through Figure 1 you ll see that the XAMLelements and attributes are quite straightforward and somewhat similar to whatyou may have seen in HTML. You can define the height and width of shapes,define fill colors, stroke (border) colors, and thicknesses, plus more. Noticethat 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, whichis used in ellipses) that is defined inside the element named Rectangle.Fill.

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

All the shapes and text shown in Figure 1 areplaced within an XAML container control named Canvas and arranged within it.Canvas is an absolute positioning type of layout control, which is useful whendifferent parts of an application need to be arranged precisely. Looking at theattributes defined on each of the shapes in Figure 1 you ll see Canvas.Top andCanvas.Left attributes defined. These attached property attributes are usedto position the element relative to the parent Canvas container, with 0,0 beingthe 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 childrenof Canvas will still be positioned properly within it.

In addition to the Canvas control, Silverlightprovides several other types of layout controls that provide more flexiblelayout options, such as StackPanel and Grid. I ll discuss these controls in anupcoming article, and provide additional details about how to use them.

Interacting with XAML

Although it s convenient to be able to defineshapes and text using XAML, applications need to be able to interact with XAMLprogrammatically to perform a variety of operations. For example, when a usermoves their mouse over an ellipse, you may want to change the fill color orperform some other type of task. Interacting with XAML is fairlystraightforward in Silverlight, and in many ways is a lot like interacting withASP.NET server controls using JavaScript, C#, or Visual Basic. You can handleclick events, mouse enter and leave events, plus much more.

To change the fill color of an ellipse as a usermoves their mouse over it you can add MouseEnter and MouseLeave eventdefinitions on the Ellipse tag in the XAML file, and define C# or Visual Basicevent handlers to handle the events. Here s an example of defining MouseEnterand 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 andMouseLeave events to change the fill color of the ellipse. The code accessesthe Ellipse control by name, then creates a SolidColorBrush and associatedcolor, which is assigned to the Fill property.

private void MyEllipse_MouseEnter(object sender, MouseEventArgse)

{

MyEllipse.Fill = newSolidColorBrush(Colors.Red);

}

private void MyEllipse_MouseLeave(object sender, MouseEventArgse)

{

MyEllipse.Fill = newSolidColorBrush(Colors.Blue);

}

Figure 3: Handling events and interactingwith XAML

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

<TextBox x:Name="FirstName" Height="20"Width="200" />

<Button x:Name="SubmitButton" Height="20"Width="100"

Click="SubmitButton_Click"Content="Click Me!" />

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

Figure 5 shows a Click event handler namedSubmitButton_Click that is used to display the text entered into the TextBoxcontrol using a MessageBox.

private void SubmitButton_Click(object sender, RoutedEventArgs e)

{

MessageBox.Show("Clicked the button");

}

Figure 5: Handling a Button control s Clickevent

Looking through the code in Figures 4 and 5 you llsee that it s much like working with standard ASP.NET controls and theirassociated event handlers. Silverlight shapes and controls are defined in XAMLmuch like ASP.NET controls are defined in an aspx page. Event handlers aredefined in a code-beside file and can interact with the different controls.

Conclusion

In this article you ve been introduced to thefundamentals 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 needto be careful to case your tags consistently, close your tags, and quote yourattributes.

Many different types of objects can be definedusing XAML, ranging from layout controls such as Canvas, shapes and textcontrols, and even user input controls. In the next article we ll continue ourdiscussion of XAML and jump into the world of layout controls. I ll provideexamples of using Canvas, Grid, StackPanel, and Border controls.

Source codeaccompanying this article is available for download.

Dan Wahlin, a MicrosoftMVP for ASP.NET and XML Web services, founded the XML for ASP.NET Developers websiteand The Wahlin Group (www.TheWahlinGroup.com),which specializes in .NET, Silverlight, and SharePoint consulting and trainingsolutions.

Add a Comment

There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement




Comments from the DevConnections Community

Join our community of development pros.

Windows problem

I all, I have a problem on my Windows Vista that began afetr the purchase of an external Hard Disk Freecom. A few days afetr the purchase I discon...

Most Recent Posts

GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS