Powered by

US - English
NEW! Silverlight 5 is available Learn More

Text and Rich Text

By Microsoft Silverlight Team|June 21, 2010|Level 200 : Novice

Summary

Silverlight provides several controls for rendering text, along with a set of properties for formatting the text. The text-based controls available in Silverlight are TextBlock, TextBox, RichTextBox, PasswordBox, and AutoCompleteBox. Except for AutoCompleteBox, these text controls are available in the Silverlight runtime. AutoCompleteBox is available in the Silverlight SDK. This QuickStart shows you how to get started with TextBlock, TextBox, and RichTextBox and shows you how you can use these text controls to display, enter, and edit text.

This QuickStart contains the following sections:

Choosing a Text Control

Silverlight includes three core text controls: TextBlock, TextBox, and RichTextBox. The text control that you use depends on the scenario. The following table lists some scenarios and the recommended control.

 
Scenario Recommended Control
Display plain, unformatted text. TextBlock
Display formatted text, paragraphs, hyperlinks, or inline images. RichTextBox
Enter or edit plain text, such as in a form. TextBox
Enter or edit formatted text, paragraphs, hyperlinks, or inline images. RichTextBox
Edit a document, article, or blog that requires formatting, paragraphs, hyperlinks, or inline images. RichTextBox
Apply character or paragraph formatting. RichTextBox
 

TextBlock

The TextBlock is the primary control for displaying read-only text in Silverlight applications. You can display text in a TextBlock control using its Text property.

The following XAML shows how to define a TextBlock control and set its Text property to a string.

XAML

<TextBlock Text="Hello, world!" />

The following illustration displays the result of the previous XAML.

TextBlock

You can also display a series of strings in a TextBlock, where each string has a different formatting. You can do this by using a Run element to display each string with its formatting and by separating each Run element with a LineBreak element.

The following XAML shows how to define several differently formatted text strings in a TextBlock by using Run objects separated with a LineBreak.

XAML

<Canvas> 
<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 result of the previous XAML.

Adding the Text Property

For more information about TextBlock, see Text and Fonts and TextBlock.

TextBox

You can use a TextBox control to enter and edit single-format and multi-line text. You can use the TextBox.Text property to set the text in a TextBox. In the following example, there are four text boxes. When you enter text in the first TextBox, the same text is displayed in the second TextBox. This is implemented using the TextChanged event. The third TextBox, which is a search-type TextBox, displays a watermark text. To implement the watermark text, you can use various font properties, such as Foreground and FontSize, and events, such as GotFocus and LostFocus. The fourth TextBox is styled using the LinearGradientBrush.

XAML

<StackPanel x:Name="LayoutRoot" Background="White">
    <TextBlock  Margin="20,20,0,0" Text="Type Text Here" />
    <TextBox  x:Name="ReadWriteTB" TextChanged="ReadWriteTB_TextChanged"
        IsReadOnly="False" HorizontalAlignment="Left" 
        Margin="20,5,0,0" Height="35" Width="200" />
    <TextBlock  Margin="20,20,0,0" Text="Read Only TextBox" />
    <TextBox x:Name="ReadOnlyTB"  IsReadOnly="True" HorizontalAlignment="Left" 
        Margin="20,5,0,0" Height="35" Width="200" />
    <TextBlock Margin="20,30,0,0" Text="Search Type TextBox" />
    <TextBlock Margin="20,0,0,0" FontSize="11">
        The following text box has a watermark text (Search). The text is gray until 
        you click inside the text box. 
        <LineBreak />
        When you click inside the text box the watermark text is removed and the 
        cursor appears ready for input.
    </TextBlock>
    <TextBox x:Name="SearchTB" Margin="20,5,0,0" Text="Search" 
        HorizontalAlignment="Left" Height="35" Width="200" 
        Foreground="Gray" GotFocus="SearchTB_GotFocus" 
        LostFocus="SearchTB_LostFocus" />
    <TextBlock Margin="20,40,0,0" Text="Demonstrating styles for TextBox" />
    <TextBlock Margin="20,0,0,0" FontSize="11">
        Select the following text to view the results of SelectionForeground and 
        SelectionBackground properties.
    </TextBlock>
    <TextBox Text="Styles" Margin="20,5,0,0" HorizontalAlignment="Left" Width="200" 
        Height="35" FontFamily="Arial" 
        FontSize="15" Foreground="White" Background="Black" BorderBrush="White" 
        SelectionForeground="Black">
        <TextBox.SelectionBackground>
            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                <GradientStop Color="Gray" Offset="0.0" />
                <GradientStop Color="White" Offset="1.0" />
            </LinearGradientBrush>
        </TextBox.SelectionBackground>
    </TextBox>
</StackPanel>

C#

//The following method displays the text entered in ReadWriteTB in ReadOnlyTB.
private void ReadWriteTB_TextChanged(object sender, RoutedEventArgs e)
{
    ReadOnlyTB.Text = ReadWriteTB.Text;
}

//The foreground color of the text in SearchTB is set to Magenta when SearchTB
//gets focus.
private void SearchTB_GotFocus(object sender, RoutedEventArgs e)
{
    SearchTB.Text = "";
    SolidColorBrush Brush1 = new SolidColorBrush();
    Brush1.Color = Colors.Magenta;
    SearchTB.Foreground = Brush1;

}

//The foreground color of the text in SearchTB is set to Blue when SearchTB
//loses focus. Also, if SearchTB loses focus and no text is entered, the
//text "Search" is displayed.
private void SearchTB_LostFocus(object sender, RoutedEventArgs e)
{
    if (SearchTB.Text == String.Empty)
    {
        SearchTB.Text = "Search";
        SolidColorBrush Brush2 = new SolidColorBrush();
        Brush2.Color = Colors.Blue;
        SearchTB.Foreground = Brush2;
    }
}

Visual Basic

'The following method displays the text entered in ReadWriteTB in ReadOnlyTB.
Private Sub ReadWriteTB_TextChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
    ReadOnlyTB.Text = ReadWriteTB.Text
End Sub

'The foreground color of the text in SearchTB is set to Magenta when SearchTB
'gets focus.
Private Sub SearchTB_GotFocus(ByVal sender As Object, ByVal e As RoutedEventArgs)
    SearchTB.Text = ""
    Dim Brush1 As SolidColorBrush = New SolidColorBrush
    Brush1.Color = Colors.Magenta
    SearchTB.Foreground = Brush1
End Sub

'The foreground color of the text in SearchTB is set to Blue when SearchTB
'loses focus. Also, if SearchTB loses focus and no text is entered, the
'text "Search" is displayed.
Private Sub SearchTB_LostFocus(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If (SearchTB.Text = String.Empty) Then
        SearchTB.Text = "Search"
        Dim Brush2 As SolidColorBrush = New SolidColorBrush
        Brush2.Color = Colors.Blue
        SearchTB.Foreground = Brush2
    End If
End Sub

RichTextBox

RichTextBox is a control that enables you to display, enter, or edit rich content, including formatted text (bold, italic, underline, font family, font size, and font color), paragraphs, hyperlinks, and inline images. It also includes clipboard support, text highlighting, and bi-directional text for input and output.

The following example creates a RichTextBox in XAML with some pre-populated, formatted content. You can enter and format text. You can also enter hyperlinks and images.

The following sections describe some of the features of the RichTextBox using the previous example.

Formatting

You can use various properties of RichTextBox to apply bold, italic, underline, font type, font size, and font color formatting to selected text. To apply formatting, you use the TextSelection.ApplyPropertyValue method on the selected text in the RichTextBox. This method takes in appropriate dependency property and property value as parameters and applies the property with the specified value to the selected text in the RichTextBox. The following table summarizes the dependency property and the property value that you can use to apply the formatting.

 
Formatting Dependency Property Property Value
Bold FontWeightProperty Use the FontWeights.Bold property to apply bold formatting to selected text. Use FontWeights.Normal to remove bold formatting from selected text.
Italic FontStyleProperty Use the FontStyles.Italic property to apply italic formatting to selected text. Use FontStyles.Normal to remove italic formatting from selected text.
Underline TextDecorationsProperty Use the TextDecorations.Underline property to apply underline formatting to selected text. Set TextDecorationsProperty to null to remove underline formatting from selected text.
Font Type FontFamilyProperty Use a FontFamily object constructed with the desired font name to specify the font.
Font Size FontSizeProperty Use a double value to specify the font size.
Font Color ForegroundProperty Use a SolidColorBrush object to specify the desired color.
 

A common scenario with a RichTextBox is to select a portion of the content, and then apply formatting to the selection. A selection of text in the RichTextBox is represented by the TextSelection class. You can access the currently selected text in the RichTextBox by using its Selection property. To perform operations on the selected text, you can use the GetPropertyValue and ApplyPropertyValue methods. The following example shows how to apply bold, italic, and underline formatting to the selected text.

XAML

<Grid x:Name="LayoutRoot" Background="White">
    <RichTextBox HorizontalAlignment="Left" Margin="63,31,0,0" x:Name="MyRTB" 
        VerticalAlignment="Top" Width="267" Height="173" />
    <Button Content="B" Height="23" HorizontalAlignment="Left"
        Margin="137,255,0,0" Name="BtnBold" VerticalAlignment="Top"
        Width="27" Click="BtnBold_Click" />
    <Button Content="I" Height="23" HorizontalAlignment="Left"
        Margin="181,255,0,0" Name="BtnItalic" VerticalAlignment="Top"
        Width="27" Click="BtnItalic_Click" />
    <Button Content="U" Height="23" HorizontalAlignment="Left"
        Margin="220,255,0,0" Name="BtnUnderline" VerticalAlignment="Top"
        Width="27" Click="BtnUnderline_Click" />
</Grid>

C#

private void BtnBold_Click(object sender, RoutedEventArgs e)
{
    if (MyRTB != null)
    {
        if (MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty) is FontWeight && 
        ((FontWeight)MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty)) == 
        FontWeights.Normal)
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty, 
                FontWeights.Bold);
        else
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty,
                FontWeights.Normal);
    }
}

private void BtnItalic_Click(object sender, RoutedEventArgs e)
{
    if (MyRTB != null)
    {
        if (MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty) is FontStyle && 
        ((FontStyle)MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty)) == 
        FontStyles.Normal)
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty, 
                FontStyles.Italic);
        else
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty,
                FontStyles.Normal);
    }
}

private void BtnUnderline_Click(object sender, RoutedEventArgs e)
{
    if (MyRTB != null)
    {
        if (MyRTB.Selection.GetPropertyValue(Run.TextDecorationsProperty) == null)
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, 
                TextDecorations.Underline);
        else
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, null);
    }
}

Visual Basic

Private Sub BtnBold_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If MyRTB IsNot Nothing Then
        If TypeOf MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty) Is FontWeight _
        AndAlso DirectCast(MyRTB.Selection.GetPropertyValue(Run.FontWeightProperty), _
        FontWeight) = FontWeights.Normal Then
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty, _
                FontWeights.Bold)
        Else
            MyRTB.Selection.ApplyPropertyValue(Run.FontWeightProperty, _
                FontWeights.Normal)
        End If
    End If
End Sub

Private Sub BtnItalic_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If MyRTB IsNot Nothing Then
        If TypeOf MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty) Is FontStyle _
        AndAlso DirectCast(MyRTB.Selection.GetPropertyValue(Run.FontStyleProperty), _
        FontStyle) = FontStyles.Normal Then
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty, _
                FontStyles.Italic)
        Else
            MyRTB.Selection.ApplyPropertyValue(Run.FontStyleProperty, _
                FontStyles.Normal)
        End If
    End If
End Sub

Private Sub BtnUnderline_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If MyRTB IsNot Nothing Then
        If MyRTB.Selection.GetPropertyValue(Run.TextDecorationsProperty) Is Nothing Then
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, _
                TextDecorations.Underline)
        Else
            MyRTB.Selection.ApplyPropertyValue(Run.TextDecorationsProperty, Nothing)
        End If
    End If
End Sub

Hyperlinks

You can use the Hyperlink element to display hyperlinks in a RichTextBox. Hyperlinks provide built-in mouse-over behavior and focus support. Use the NavigateUri property of the Hyperlink element to specify the URL.

You must set the IsReadOnly property of RichTextBox to true for the Hyperlink element to be active.

The following example shows how to create a RichTextBox with a Hyperlink in XAML and code.

XAML

<Button Content="Insert Hyperlink" Height="23" HorizontalAlignment="Left" 
Margin="211,218,0,0" Name="BtnHyperlink" VerticalAlignment="Top" 
Width="110" Click="BtnHyperlink_Click"/>

C#

private void BtnHyperlink_Click(object sender, RoutedEventArgs e)
{
    Hyperlink MyLink = new Hyperlink();
    MyLink.Inlines.Add("Hyperlink");
    MyLink.NavigateUri = new Uri("http://www.msdn.com");
    Paragraph MyPg = new Paragraph();
    MyPg.Inlines.Add(MyLink);
    MyRTB.Blocks.Add(MyPg);
}

Visual Basic

Private Sub BtnHyperlink_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim MyLink As New Hyperlink()
    MyLink.Inlines.Add("Hyperlink")
    MyLink.NavigateUri = New Uri("http://www.msdn.com")
    Dim MyPg As New Paragraph()
    MyPg.Inlines.Add(MyLink)
    MyRTB.Blocks.Add(MyPg)
End Sub

Images and other UIElements

You can display a UIElement, such as an Image or a Button, in a RichTextBox using InlineUIContainer. This enables rich-text scenarios, such as displaying content from a chat client and showing emoticons. UI elements are active when the RichTextBox is in read-only mode and inactive in edit mode. For example, they can respond to input and receive focus only when they are in read-only mode.

The following example shows how to add an image to a RichTextBox.

XAML

<Button Content="Insert Image" Height="23" HorizontalAlignment="Left"
Margin="79,218,0,0" Name="BtnImage" VerticalAlignment="Top"
Width="110" Click="BtnImage_Click"/>

C#

private void BtnImage_Click(object sender, RoutedEventArgs e)
{
    Image MyImage = new Image();
    MyImage.Source = new BitmapImage(new Uri("Desert.jpg",
        UriKind.RelativeOrAbsolute));
    MyImage.Height = 50;
    MyImage.Width = 50;
    InlineUIContainer MyUI = new InlineUIContainer();
    MyUI.Child = MyImage;

    Paragraph MyPg = new Paragraph();
    MyRTB.Blocks.Add(MyPg);
    MyPg.Inlines.Add(MyUI);
}

Visual Basic

Private Sub BtnImage_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim MyImage As New Image()
    MyImage.Source = New BitmapImage(New Uri("Desert.jpg", _
        UriKind.RelativeOrAbsolute))
    MyImage.Height = 50
    MyImage.Width = 50
    Dim MyUI As New InlineUIContainer()
    MyUI.Child = MyImage
    
    Dim MyPg As New Paragraph()
    MyRTB.Blocks.Add(MyPg)
    MyPg.Inlines.Add(MyUI)
End Sub

Other features of RichTextBox

You can perform other advanced functions in RichTextBox, such as programmatically traversing and selecting the content; getting and setting the XAML representation of the content in a RichTextBox; and right-to-left layout. For more information about RichTextBox and these features, see RichTextBox Overview, RichTextBox, and Silverlight Text Editor Sample.

See Also

What's Next

Now that you are familiar with the basic UI components of controls and text, it's time to position them where you want in your application: Layout QuickStart.

Microsoft Silverlight Team

By Microsoft Silverlight Team, Silverlight is a powerful development platform for creating engaging, interactive user experiences for Web, desktop, and mobile applications when online or offline.

Comments (0)