Export (0) Print
Expand All

Silverlight Text and Fonts Overview

Microsoft Silverlight provides several elements for rendering text, along with a set of properties for creating a variety of formatted text.

This topic contains the following sections:

Text Elements

The TextBlock object is the primary element for displaying text in Silverlight-based applications. The following XAML example shows how to define a TextBlock element and set its Text property to a character string.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock Text="Hello, world!" />
</Canvas>

The following illustration displays the result of the previous XAML content example.

TextBlock rendering with default font properties

TextBlock rendering with default font properties

There are several interesting items to note about the rendered text:

  • The default value of the FontSize property of the rendered TextBlock is 14.666 pixels, which is exactly 11 points.
  • The default value of the FontFamily property of the rendered TextBlock is "Lucida Sans Unicode, Lucida Grande".
  • No font files are required on the hosting Web server, or residing in the same directory location as the XAML content, to enable the default font.

When setting text in a TextBlock, it is not necessary to specify the Text property explicitly in XAML.

XAML
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">
  <TextBlock>Hello, world!</TextBlock>
</Canvas>

Note   Leading or trailing white space is not preserved when setting the Text property.

Specifying Font Attributes

The following table lists the font attributes that can be applied to text elements such as a TextBlock.

Property Description Default Value
FontFamily Represents a set of typefaces that share the same family name, such as "Times New Roman", but that differ in features. These feature differences include FontStyle, such as italic, and FontWeight, such as bold. The default value is "Portable User Interface", which is used as an alias for the font family value of "Lucida Sans Unicode, Lucida Grande".
FontSize Specifies a non-negative value as the desired font size in pixels. The default value is 14.666 pixels, which is exactly 11 points.
FontStretch Describes the degree to which a font form is stretched from its normal aspect ratio, which is the original width to height ratio specified for the glyphs in the font. The default value is Normal.
FontStyle Specifies whether the font style is normal or italic. The default value is Normal.
FontWeight Describes the relative weight of a font, in terms of the lightness or heaviness of the strokes. The default value is Normal.

The following XAML example shows how to define a TextBlock element and set all of the above font attributes.

XAML
<TextBlock
  Text="Font Attributes"
  FontFamily="Verdana"
  FontSize="36"
  FontStretch="UltraExpanded"
  FontStyle="Italic"
  FontWeight="ExtraBlack" />

The following illustration displays the result of the previous XAML content example.

TextBlock rendering with defined font property values

TextBlock rendering with defined font property values

Note   The property values that are set for font attributes may not be the ones used during rendering because of font fallback.

Supported Fonts

The following illustration shows the nine fonts that are supported by Silverlight text elements.

Supported fonts for text elements

Supported fonts for text elements

The SetFontSource method can be used to add downloaded font content to the existing collection of typefaces for Silverlight text elements. The downloaded content can either be an individual font file or packaged content, such as a .zip file, which contains one or more font files. For more information, see Using SetFontSource for Downloaded Fonts.

Using the Run and LineBreak Objects

The Run object is a text element that represents a discrete section of formatted or unformatted text. The LineBreak object represents an explicit new line in a TextBlock. The following XAML example shows how to define several differently formatted text strings within a TextBlock by using Run objects.

XAML
<!-- Display formatted text as Run objects within a TextBlock. -->
<Canvas
  xmlns="http://schemas.microsoft.com/client/2007">

<TextBlock
  FontFamily="Arial" Width="400" Text="Sample text formatting runs">
  <LineBreak/>
  <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
  <LineBreak/>
  <Run Foreground="Teal" FontFamily="Times New Roman" FontSize="18" FontStyle="Italic">Times New Roman Italic 18</Run>
  <LineBreak/>
  <Run Foreground="SteelBlue" FontFamily="Verdana" FontSize="14" FontWeight="Bold">Verdana Bold 14</Run>
</TextBlock>

</Canvas>

The following illustration shows the rendered formatted text from the previous XAML content example.

TextBlock rendering multiple Run objects

TextBlock rendering multiple Run objects

Notice that the LineBreak object forces the text in each Run to display on a separate line. Without the LineBreak object, the text in each Run would flow together as one line and would eventually be truncated after exceeding the TextBlock object's Width value. The following illustraton shows how the formatted text would render without using LineBreak objects.

TextBlock rendering multiple Run objects without LineBreak objects

TextBlock rendering multiple Run objects without LineBreak objects

Formatting Text

In addition to selecting font attributes for text elements, you can format text by using text-specific properties such as Foreground, TextWrapping, and TextDecorations.

Using the Foreground Property

The Foreground property enables you to specify a Brush for the rendered text. A Brush can represent a solid color, a linear or radial gradient, or an image. The following XAML example shows how to set the Foreground property to a solid color and a linear gradient. Notice that the Foreground property can also be used in a Run object to display a different color than the TextBlock object's Foreground property value.

XAML
<!-- TextBlock with a single brush applied to the text. -->
<TextBlock
  FontSize="32"
  FontWeight="Bold"
  Foreground="Maroon">
  Maroon
</TextBlock>

<!-- TextBlock with three brushes applied to the text. -->
<TextBlock
  Canvas.Top="60"
  FontFamily="Arial"
  FontSize="32"
  FontWeight="Bold"
  Foreground="Navy">
  Navy
  <Run Text="DodgerBlue " Foreground="DodgerBlue"/>
  <Run Text="LightSteelBlue " Foreground="LightSteelBlue"/>
</TextBlock>

<!-- TextBlock with a linear gradient brush applied to the text. -->
<TextBlock
  Canvas.Top="100"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold">
  LINEAR GRADIENT BRUSH
  <TextBlock.Foreground>
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
      <GradientStop Color="Red" Offset="0.0" />
      <GradientStop Color="Orange" Offset="0.2" />
      <GradientStop Color="Yellow" Offset="0.4" />
      <GradientStop Color="Green" Offset="0.6" />
      <GradientStop Color="Blue" Offset="0.8" />
      <GradientStop Color="Violet" Offset="1.0" />
    </LinearGradientBrush>
  </TextBlock.Foreground>
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleY="3.0" />
  </TextBlock.RenderTransform>
</TextBlock>

The following illustration shows the rendered text from the previous XAML example. Notice the effect of applying a ScaleTransform to the last line of rendered text. For more information about applying a RenderTransform to a TextBlock, see Applying Transforms to Text.

TextBlocks rendering solid color and linear gradient brushes

TextBlocks rendering solid color and linear gradient brushes

The Foreground property of the TextBlock can also specify an ImageBrush. The following XAML example shows how to set the Foreground property of an ImageBrush whose image is used as the fill for the TextBlock's rendered text.

XAML
<!-- TextBlock with an image brush applied to the text. -->
<TextBlock
  Canvas.Top="120"
  FontFamily="Verdana"
  FontSize="72"
  FontStyle="Italic"
  FontWeight="Bold">
  SHRUBBERY
  <TextBlock.Foreground>
    <ImageBrush ImageSource="forest.jpg"/>
  </TextBlock.Foreground>
</TextBlock>

The following illustration shows the rendered text from the previous XAML example.

TextBlock rendering an image brush

TextBlock rendering an image brush

Wrapping Text

The TextWrapping property indicates how text should wrap in a TextBlock. The TextWrapping enumeration defines the values listed in the following table.

Value Description
NoWrap No line wrapping is performed.
Wrap Line breaking occurs if the line overflows beyond the available block width, even if the standard line-breaking algorithm cannot determine any line-break opportunity, as in the case of a very long word that is constrained in a fixed-width container with no scrolling allowed.

The following XAML example shows how to set the TextWrapping property to NoWrap and Wrap.

XAML
<!-- TextBlock with no text wrapping -->
<TextBlock
  Text="The quick red fox jumped over the lazy brown dog."
  Width="200"
  TextWrapping="NoWrap" />

<!-- TextBlock with text wrapping -->
<TextBlock
  Canvas.Top="40"
  Text="The quick red fox jumped over the lazy brown dog."
  Width="200"
  TextWrapping="Wrap" />

The following illustration shows the rendered text from the previous XAML example.

TextBlock rendering non-wrapped and wrapped text

TextBlock rendering non-wrapped and wrapped text

ActualHeight and ActualWidth are read-only properties that specify the rendered height and width of the TextBlock. These properties can be different from the Height and Width properties of the TextBlock. Setting the TextWrapping property affects the ActualHeight and ActualWidth values of the TextBlock. The following illustration shows how the TextWrapping property affects ActualHeight and ActualWidth.

How TextWrapping affects ActualWidth and ActualHeight

How TextWrapping affects ActualWidth and ActualHeight

Using Text Decorations

By using the TextDecorations property, you can create the visual appearance of a hyperlink in a Run or TextBlock object.

Simulating a hyperlink by using the TextDecorations property

Simulating a hyperlink by using the TextDecorations property

The following XAML example shows how to define a TextBlock that simulates a hyperlink by displaying an underline in response to the MouseEnter event. The underline is removed in response to the MouseLeave event. Notice that the Cursor property is set to display the Hand cursor when the mouse pointer is over the TextBlock.

XAML
<TextBlock
  Text="Click to Win!"
  TextDecorations="None"
  Cursor="Hand"
  FontSize="14" FontWeight="Bold"
  MouseEnter="onMouseEnter"
  MouseLeave="onMouseLeave"
  MouseLeftButtonUp="onMouseLeftButtonUp" />

The following JavaScript example shows the corresponding event-handling functions for the TextBlock defined in the previous XAML example.

JavaScript
function onMouseEnter(sender, mouseEventArgs)
{
    sender.textDecorations = "Underline";
    sender.foreground="Maroon";
}

function onMouseLeave(sender, mouseEventArgs)
{
    sender.textDecorations = "None";
    sender.foreground="Black";
}

function onMouseLeftButtonUp(sender, mouseEventArgs)
{
    alert("Congratulations!");
}

Applying Transforms to Text

Transforms can alter the display of text in your application. The following examples use different types of rendering transforms to affect the display of text in a TextBlock.

Using a RotateTransform

The following illustration shows text that is rotated 90 degrees by using a RotateTransform.

TextBlock that uses a RotateTransform

TextBlock that uses a RotateTransform

The following code example uses a RotateTransform to rotate text. An Angle value of 90 rotates the element 90 degrees clockwise.


XAML
<!-- Rotate the text 90 degrees using a RotateTransform. -->
<TextBlock Text="Rotated Text" FontSize="32" Foreground="Teal">
  <TextBlock.RenderTransform>
    <RotateTransform Angle="90" />
  </TextBlock.RenderTransform>
</TextBlock>

Using a ScaleTransform

The following example shows the second line of text scaled by 150% along the x-axis, and the third line of text scaled by 150% along the y-axis.

TextBlock that uses a ScaleTransform

TextBlock that uses a ScaleTransform

The following XAML example uses a ScaleTransform to scale text from its original size.


XAML
<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold" 
  Foreground="SteelBlue"
  Text="Scaled Text" />

<!-- Scale the text width using a ScaleTransform. -->
<TextBlock
  Canvas.Top="40"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold" 
  Foreground="SteelBlue"
  Text="Scaled Text">
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleX="1.5" ScaleY="1.0" />
  </TextBlock.RenderTransform>
</TextBlock>

<!-- Scale the text height using a ScaleTransform. -->
<TextBlock
  Canvas.Top="80"
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold" 
  Foreground="SteelBlue"
  Text="Scaled Text">
  <TextBlock.RenderTransform>
    <ScaleTransform ScaleX="1.0" ScaleY="1.5" />
  </TextBlock.RenderTransform>
</TextBlock>

Note   Scaling text is not the same as increasing the font size of text. Font sizes are calculated independently to provide the best resolution at different sizes. Scaled text, on the other hand, preserves the proportions of the original sized text

Using a SkewTransform

The following example shows text skewed along the x-axis.

TextBlock that uses a SkewTransform

TextBlock that uses a SkewTransform

The following code example uses a SkewTransform to skew text. A skew, also known as a shear, is a transformation that stretches the coordinate space in a non-uniform manner. In this example, the two text strings are skewed -30 degrees and 30 degrees along the x-coordinate.


XAML
<!-- Skew the text using a SkewTransform. -->
<TextBlock
  FontSize="32"
  FontWeight="Bold" 
  Foreground="Maroon"
  Text="Skewed Text">
  <TextBlock.RenderTransform>
    <SkewTransform AngleX="-30" AngleY="0" />
  </TextBlock.RenderTransform>
</TextBlock>

<TextBlock
  Canvas.Top="60"
  FontSize="32"
  FontWeight="Bold" 
  Foreground="Maroon"
  Text="Skewed Text">
  <TextBlock.RenderTransform>
    <SkewTransform AngleX="30" AngleY="0" />
  </TextBlock.RenderTransform>
</TextBlock>

Using a TranslateTransform

The following example shows text translated, or moved, along the x- and y-axis.

TextBlock that uses a TranslateTransform

TextBlock that uses a TranslateTransform

The following code example uses a TranslateTransform to offset text. In this example, a slightly offset copy of text below the primary text creates a shadow effect.


XAML
<!-- Offset the text using a TranslateTransform. -->
<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold" 
  Foreground="Black"
  Text="Translated Text">
  <TextBlock.RenderTransform>
    <TranslateTransform X="2" Y="2" />
  </TextBlock.RenderTransform>
</TextBlock>

<TextBlock
  FontFamily="Verdana"
  FontSize="32"
  FontWeight="Bold" 
  Foreground="Coral"
  Text="Translated Text"/>

Using SetFontSource for Downloaded Fonts

The SetFontSource method can be used to add downloaded font content to the existing collection of typefaces for a TextBlock object. The downloader parameter identifies the Downloader object that represents the downloaded content. The downloaded content can either be an individual font file or packaged content, such as a .zip file, which contains one or more font files.

Note   Font files used with the SetFontSource method must be OpenType or TrueType fonts.

Note   As with most types of software, font files are licensed, rather than sold, and licenses that govern the use of fonts vary from vendor to vendor. As a developer it is your responsibility to ensure that you have the required license rights for any font you embed within a document or application, or otherwise redistribute.

The following JavaScript example shows how to use the Downloader object to download an individual font file.

JavaScript
// Event handler for initializing and executing a font file download request.
function onMouseLeftButtonUp(sender, eventArgs)
{
    // Retrieve a reference to the plug-in.
    var plugin = sender.getHost();

    // Create a Downloader object.
    var downloader = plugin.createObject("downloader");

    // Add Completed event.
    downloader.addEventListener("Completed", onCompleted);

    // Initialize the Downloader request.
    downloader.open("GET", "SHOWG.TTF");

    // Execute the Downloader request.
    // NOTE: downloader APIs disallow file:\\ scheme
    // you must run this sample over localhost: or off a server or the following call will fail
    downloader.send();
}

When the font file has been downloaded, it needs to be added to the TextBlock object's collection of typefaces. When it has been added to the collection, it can be selected by using the FontFamily property. The following JavaScript example shows how to use the SetFontSource method to add the the font file to the typeface collection, and then set the FontFamily property to display the TextBlock with the downloaded font.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";

    myTextBlock.text = "Showcard Gothic";
}

You can also download font files that are contained in a packaged format such as a .zip file. The .zip file can contain other content files, such as image files.

Zip file packages can contain font image files

Zip file packages can contain font image files

The following JavaScript example shows how to use the Downloader object to download a .zip file that contains an image file and multiple font files.

JavaScript
// Initialize the Downloader request. Zip file contains: Coco.png, Britanic.ttf, Erasbd.ttf, Showg.ttf
downloader.open("GET", "myMediaAssets.zip");

When the .zip file has been downloaded, the font files it contains must be added to the TextBlock object's collection of typefaces. When the font files have been added to the collection, they can be selected by using the FontFamily property. The following JavaScript example shows how to use the SetSource and SetFontSource methods to use the downloaded content.

JavaScript
// Event handler for the Completed event.
function onCompleted(sender, eventArgs)
{
    // Retrieve the Image object.
    var myImage = sender.findName("myImage");

    // Set the Source property of the Image object to the specific image
    // within the downloaded Zip package file.
    myImage.setSource(sender, "Coco.png");

    // Retrieve the TextBlock object.
    var myTextBlock = sender.findName("myTextBlock");

    // Add the font files in the downloaded package object to the TextBlock's type face collection.
    myTextBlock.setFontSource(sender);

    // Set the FontFamily property to the friendly name of the font.
    myTextBlock.fontFamily = "Showcard Gothic";
}

To return to the default font that is used to display the TextBlock, set the downloader parameter of the SetFontSource method to null. The following JavaScript example shows how to use the SetFontSource method with a null parameter value.

JavaScript
// Retrieve the TextBlock object.
var myTextBlock = sender.findName("myTextBlock");

// Remove the custom font setting.
myTextBlock.setFontSource(null);

If you want to package fonts in .zip files, you should initiate the downloader in such a way that the same downloader instance is used to provide the fonts, and that instance is retained. This is in contrast to the performance advice generally given for the downloader, which suggests that you null out the downloader after each completed download. Here, however, you want the downloader to persist, because the downloader will retain the last download and provide some degree of caching for fonts. This practice can provide a noticeable benefit for large font files or large numbers of SetFontSource calls.


Animating Text

The value of many text properties can be animated including the text size, position, and color (see Animation Overview for more information).

Performance Tip   Animating the size of text can potentially use a lot of system resources. This is because when Silverlight renders text, it uses hinting to smooth each text glyph. If you animate the text size (by using a Transform or FontSize), Silverlight will hint the glyphs for each frame, which is costly and could cause frame dropping. If your application requires dynamic scale changes of large text, it may be better to use vector graphics to represent the text.


Inputting Text

Silverlight version 1.0 does not have a TextBox control. To input text into a Silverlight-based application, you can overlay an HTML control such as TEXTAREA over your Silverlight-based application. You would then use JavaScript to pass the inputted text back and forth between the Silverlight-based application and the HTML control (TEXTAREA). See Mixing Object Models for an example. Also, see Using Input Method Editors for Text Entry in Silverlight for a video that shows how to allow user text input.

See Also

LineBreak
Run
TextBlock
Overviews and How-to Topics

Community Additions

Show:
© 2014 Microsoft