Using Text in XAML

7/25/2010 5:09:58 PM
I_section1_d1e1655.html ScriptWeb1
Introducing XAML

XAML is an XML dialect, you'll see a lot of angle brackets here and throughout this book. In this chapter, we will have a look at the most important XAML elements. It is virtually impossible to cover them all in a book of this size, but we will present as many as possible to let you dive into XAML with maximum speed and get a sense of the power of Silverlight markup.

If you have already worked with XAML for WPF applications, you already know most of what is covered in this chapter . However, there are some subtle differences: Silverlight does not support the full XAML format of WPF does, but only a (quite decent) subset. Future releases of Silverlight will increase the percentage of supported WPF elements and attributes, but some things just cannot work in a web browser as they do in a desktop application.

<Canvas xmlns=""

If you are using the Silverlight Project template, the original structure looks different:
<UserControl x:Class="HelloWorld.Page"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">

To facilitate a migration to the script template, most examples will use  as the first element, either in the form of the root element (script template) or as the first element within (project template). Whatever way you prefer, always remember to put the correct namespaces at the beginning.

Using Text

The first example used to introduce most technologies is some variation of "Hello World" . The element used for this is, and there are two ways to provide this text:

  • Within the Text attribute of the element

  • As a text node within the element

Example 1 uses the latter approach to output some simple text. Note that using text within was not allowed in older Silverlight versions, but it worked nevertheless; Figure 1 proves that it still does.

Example 1. Using simple text, the XAML file (Page.xaml, project Text1)

<UserControl x:Class="Text1.Page"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">

If you are using the web site and do not want to rely on the Extensions, there is an alternative approach. First, you need JavaScript code that initializes the Silverlight content. The SDK and the script templates contain a file called Silverlight.js that provides you with the functionality to embed Silverlight content into an HTML page. The page hosting the Silverlight content uses the Silverlight.js file and calls one of its methods, Silverlight.createObjectEx(), as you can see in Example 2. For most of the remainder of this book, we will use the project-based template; however, it requires little effort to port these examples to the script web site template.

Example 2. Using simple text, the JavaScript code (excerpt from Default.html, project ScriptWeb)

if (!window.Silverlight) 
window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
return function() {
return method.apply(instance, arguments);

var scene = new ScriptWeb1.Scene();

source: 'Scene.xaml',
parentElement: document.getElementById('silverlightPlugInHost'),
id: 'silverlightPlugIn',
properties: {
width: '100%',
height: '100%',
version: '1.0'
events: {
onLoad: Silverlight.createDelegate(scene, scene.handleLoad),
onError: function(sender, args) {
var errorDiv = document.getElementById("errorLocation");
if (errorDiv != null) {
var errorText = args.errorType + "- " + args.errorMessage;

if (args.ErrorType == "ParserError") {
errorText += "
File: " + args.xamlFile;
errorText += ", line " + args.lineNumber;
errorText += " character " + args.charPosition;
else if (args.ErrorType == "RuntimeError") {
errorText += "
line " + args.lineNumber;
errorText += " character " + args.charPosition;
errorDiv.innerHTML = errorText;
context: null

Note the highlighted code elements:

  • The source property must be filled with the URL of the XAML file.

  • The parentElement property must be filled with a reference to the DOM element that will hold the Silverlight content.

  • The id property provides a value that JavaScript code may use to access the Silverlight content.

Now let's have a closer look at the HTML file that is used as the primary page to be loaded in the browser. The HTML page needs to contain a

container with the same ID that has been provided in the parentElement property. Finally, the page needs to include the JavaScript code from Example 2. 3 has the full code, and Figure1 shows the output—the text appears.

Example 3. Using simple text, the HTML file (Default.html, project ScriptWeb)


Creating new Silverlight apps starts with copying and pasting most of the time. When creating new content, you need copies of the HTML file, the XAML file, and, optionally, the XAML JavaScript file (you will see such a file in action in the following chapter). Then you just have to update all filenames and you are set. Therefore, we will print the HTML file only if it is beneficial to better understand the concept of a given example. We will also avoid reprinting the HTML file with the JavaScript code if there is no special additional information in it. The code downloads for this book always come with complete, running code.

Figure 1 shows the default layout for text: the text uses the Lucida font, has a size of 11 points, and is displayed in black. To make this possible, the font does not even have to be installed on the client (or on the server) it is part of the plug-in. Therefore, the experience on Mac OS X is almost the same, as Figure 2 shows.

Figure 1. The text is displayed

Figure 2. The same text on Mac OS X

Apart from the Lucida font, several other fonts are also supported cross-platform:

  • Arial

  • Arial Black

  • Comic Sans MS

  • Courier New

  • Georgia

  • Times New Roman

  • Trebuchet MS

  • Verdana

Other fonts, even if they are installed on the client, are not supported; Silverlight uses Lucida if the font name is invalid.


It is possible to load external OpenType or TrueType (TTF) fonts and use them within a Silverlight application.

There are several ways to apply these fonts. First of all, some of the attributes come in handy:


The font family name (e.g., Arial).


The font size in points (e.g., 12).


How to display the font (e.g., Thin, ExtraLight, Light, Normal, Medium, SemiBold, Bold, ExtraBold, Black, and ExtraBlack; unfortunately, IntelliSense provides you with additional, invalid choices).

You can easily apply these attributes to a <TextBlock> element. However, if you would like to use different formattings in one <TextBlock>, you have another option. Use the <Run> element within <TextBlock> to provide inline formatting options. This concept can be compared to HTML: imagine <TextBlock> as a <div> element and <Run> as a <span> element within that <div> element. The styles of the <div> element provide the basic layout of the text within, but <span> styles may override <div> styles.

Example 4 shows some styling options. It also introduces a new XAML element:

The <LineBreak> element

This element defines, well, a line break.

The Foreground attribute

This defines the foreground (here it is text) color. You can use a defined color name (Red, Green, Blue, etc.), or an RGB triple (#ff0000, #00ff00, #0000ff, etc.), or aRGB. The "a" stands for alphatransparency. Just provide a value between 0 (00) and 255 (ff) that defines the degree of the nontransparency. If you set it to 00, the element is fully transparent (e.g., the background is seen, the element is not). If you set it to ff, the element is not transparent at all, so you do not see the background. If you use a value in between, the background shines through at the given degree. For instance, #7fffff00 is a yellow (ffff00) that is about 50% transparent (7f is hex for 127).


You can also provide the background color for an element, using the Background property.

Refer to Figure 3 for the output in the browser.

Example 4. Text styling options, the XAML file (Page.xaml, project Text2)

Figure 3. Different text styling options

Wrapping Text

By default, the text contained in a <TextBlock> element does not wrap. However, by setting the TextWrapping property to Wrap, you can instruct Silverlight to automatically wrap the text for you. This makes most sense if you provide a fixed width for the text. For example:

<TextBlock Width="200" TextWrapping="Wrap" 
Text="This text will not fit in one line." />

Setting the TextWrapping property to NoWrap would disabled text wrapping, which is the default anyway.

Top 10
Buying Guide: CPU Cooling Equipment (Part 5) - Antec KUHLER H2O 620,Arctic Cooling Freezer i30,Cooler Master Hyper 612 PWM
Buying Guide: CPU Cooling Equipment (Part 4) - Thermaltake BigWater 760 Plus,Thermaltake Frio OCK,Zalman CNPS20LQ
Buying Guide: CPU Cooling Equipment (Part 3) - NZXT HAVIK 140,Phanteks PH-TC140PE_BL, Swiftech H20-X20 Edge HD
Buying Guide: CPU Cooling Equipment (Part 2) - Antec KUHLER H2O 920, Corsair Hydro Series H80, Corsair Hydro Series H100, Noctua NH-D14
Buying Guide: CPU Cooling Equipment (Part 1)
AMD A6-3500 - Llano integrated-graphics processors
Viewsonic VP2365-LED – Go LED, Go Green
Philips Brilliance 241P4QPYES – Not a cheap TN
Samsung Series 7 Gamer
Zalman F1-Series 240GB - New star SSD
Most View
Managing and Administering SharePoint 2010 Infrastructure : Using Additional Administration Tools for SharePoint
Binding Application Data to the UI objects in Silverlight
iPhone Application Development : Getting the User’s Attention - Generating Alerts
Understanding and Using Windows Server 2008 R2 UNIX Integration Components (part 2)
iPhone Application Development : Creating and Managing Image Animations and Sliders (part 3) - Finishing the Interface
Cisco Linksys X3000 - The Link to Connectivity
HP LaserJet Pro CM1415fnw - Print from The Clouds
Building Your First Windows Phone 7 Application (part 2) - Using Your First Windows Phone Silverlight Controls
Determine Your Need for Server Core
Mobile Application Security : Bluetooth Security - Overview of the Technology
Using System Support Tools in Vista
Windows 7 : Using Windows Live Calendar (part 3) - Scheduling Appointments and Meetings & Viewing Agendas and Creating To-Do Lists
Advanced ASP.NET : The Entity Framework (part 3) - Handling Errors & Navigating Relationships
Graham Barlow: the Apple view
Ipad : Presentations with Keynote - Adding Transitions (part 2) - Object Transitions
Windows Server 2003 : Troubleshooting Group Policy
Microsoft XNA Game Studio 3.0 : Controlling Color (part 2)
Building the WinPE Image
Programming the Mobile Web : HTML 5 (part 3) - Offline Operation
Windows Phone 7 Development : Using Culture Settings with ToString to Display Dates, Times, and Text