Click here to Skip to main content
11,805,604 members (52,504 online)
Click here to Skip to main content

Using RichTextBox in Silverlight 4

, 24 Sep 2010 CPOL 72.3K 2.4K 11
Rate this:
Please Sign up or sign in to vote.
The article discusses the RichTextBox control in Silverlight 4, and demonstrates how to use it.

Introduction and Background

Although Silverlight 4.0 was released in April 2010, numerous examples already abound for its new features. These include examples demonstrating the RichTextBox control as well. However, what I found was that most of these examples catered to runtime aspects, such as selecting user-typed text at runtime, and formatting it. The ubiquitous “text editor” and “Notepad” examples using Silverlight RichTextBox are what you'll mostly find if you did a Google search for the control. So what does one do if one wants to learn formatting a Silverlight RichTextBox at design through XAML? To answer this question, I demonstrate a simple example. Again, this example might seem rudimentary, but it solves our objective – pure XAML code demonstrating how to format the RichTextBox. I have also thrown in a couple of other elements such as an Image and Hyperlink for good measure. Following this example, I also take up a few examples to showcase other features that the RichTextBox offers.

What you will need

  • Visual Studio 2010 (any version will do).

RichTextBox control

The RichTextBox control in Silverlight 4.0 is a control that enables you to display or edit rich content. This content may include formatted paragraphs, hyperlinks, and inline images.

Creating the example

Create a Silverlight 4.0 application using Visual Studio 2010. Name it RichTextDemo. Drag and drop a RichTextBox from the ToolBox onto the MainPage. In the XAML, edit the markup such that it looks as follows:

<UserControl x:Class="RichTextDemo.MainPage"
    d:DesignHeight="500" d:DesignWidth="600">

    <Grid x:Name="LayoutRoot" Background="White" Height="450" Width="550">
        <RichTextBox HorizontalAlignment="Left" Margin="10,12,0,0" 
           Name="contentBox" VerticalAlignment="Top" Height="330" 
           Width="390" IsReadOnly="True">

Further, edit the markup for the RichTextBox as follows:

<RichTextBox HorizontalAlignment="Left" Margin="10,12,0,0" Name="contentBox" 
        VerticalAlignment="Top" Height="330" Width="390" IsReadOnly="True">
    <Paragraph FontFamily="Georgia" FontSize="12" TextAlignment="Justify">
        This photograph depicting a
        <Run Text=" flower closeup " FontStyle="Italic" 
              FontWeight="ExtraBold" /> belongs to the
        <Run Text=" macro " Foreground="Red" 
           FontWeight="ExtraBold"/> genre of photography. 
           Macro photography requires a great deal of precision. 
           You need a sharp pair of lenses to capture
        <Run Text=" high quality closeups. " 
             Foreground="DarkBlue" FontWeight="ExtraBold"/>
            <Image Height="143" HorizontalAlignment="Left" Margin="144,82,0,0" 
               Name="image1" Stretch="Uniform" VerticalAlignment="Top" Width="196" 
               Source="/RichTextDemo;component/7.jpg" UseLayoutRounding="True" />
        <Hyperlink NavigateUri="">
           Click here to read about macro photography</Hyperlink>

Let me now explain very briefly what has been done so far. The XAML markup code creates a RichTextBox, with some text, an image, and a hyperlink. A RichTextBox has a Content property comprising of Blocks, which in turn is a collection of Paragraph elements. The content of a RichTextBox may include formatted text, hyperlinks, and images. Here, in this example, to place and format the text, first I use the Paragraph element, and then the Run element. Note that the Paragraph element also has a Foreground property, which I have not used here. Instead, I use the Run element as it’s more useful to format small chunks of text. The RichTextBox control also allows you to add elements of type Span, Bold, and Underline, but they have not been used here. The Run element derives from the Inline element. An Inline cannot be used directly within a RichTextBox control; however, you can use the Run element. The LineBreak element is used to introduce line breaks. The Image is placed inside the InlineUIContainer. The NavigateUri property of Hyperlink is set to the link to which we want to redirect the user. You can have as many Paragraph and Run elements as you want in a RichTextBox control. Using a combination of Paragraph and Run elements, you can format the text in various ways. When you execute the code, you will see the following output. Note that you haven't made any changes whatsoever to the .xaml.cs (code-behind). Through pure XAML markup, you have achieved this output:

Loading a text file at runtime

What if you wanted the user to select a text file at runtime and populate its contents into the RichTextBox control? You can achieve this by using the OpenFileDialog component, some stream handling tasks, and then assigning the file contents to the RichTextBox control. First, add a button which when clicked will redirect to the next page.

<Button Content="More" Height="23" HorizontalAlignment="Left" Margin="317,405,0,0" 
        Name="btnMore" VerticalAlignment="Top" Width="75" Click="btnMore_Click" />

In MainPage.xaml.cs, add the following code:

// Call the method which will redirect to the next page
private void btnMore_Click(object sender, RoutedEventArgs e)
     MainPage ps = this;
     ps.Navigate(new Page2());

// Redirect to the next page
public void Navigate(UserControl nextPage)
    this.Content = nextPage;

Add a new page to the project by selecting Project->Add New Item and then selecting Silverlight Page. Rename the page as Page2 and add the following markup to it:

<navigation:Page x:Class="RichTextDemo.Page2" 
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Page2 Page">
    <Grid x:Name="LayoutRoot" Height="480" Width="640">
        <RichTextBox HorizontalAlignment="Left" Margin="89,64,0,0" Name="rtb" 
             VerticalAlignment="Top" Height="301" Width="416"/>
        <Button Content="Select File" Height="23" HorizontalAlignment="Left" 
             Margin="268,12,0,0" Name="btnSelect" VerticalAlignment="Top" 
             Width="75" Click="btnSelect_Click" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" 
             Name="textBlock1" Text="FileName:" VerticalAlignment="Top" Width="73" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="89,12,0,0" 
             Name="txtFile" VerticalAlignment="Top" Width="164" />
        <Button Content="Reset" Height="23" 
             HorizontalAlignment="Left" Margin="430,385,0,0" 
             Name="btnReset" VerticalAlignment="Top" Width="75" 
             Click="btnReset_Click" IsEnabled="False" />

This will create a RichTextBox, Button, TextBlock, and TextBox on the page. Add the following code to the code-behind (Page2.xaml.cs):

//Import this namespace for file handling
using System.IO;

This namespace defines the StreamReader class that will be used to read the contents of the text file. Now, add the following code in the Click event handler of btnSelect:

private void btnSelect_Click(object sender, RoutedEventArgs e)
     // Display the dialog box for user to select a file 
     OpenFileDialog odlg = new OpenFileDialog();
     // Ensure only text files are selected
     odlg.Filter = "Text files|*.txt";
     odlg.Multiselect = false;
     string contents = null;
     // Verify that a file was selected in the dialog
     if ((bool)odlg.ShowDialog())
        txtFile.Text = odlg.File.Name;
        // Read the contents of the file and assign it to the string, contents
        StreamReader reader = new StreamReader(odlg.File.OpenRead());
        while (!reader.EndOfStream)
            contents = reader.ReadToEnd();
        // Assign the contents of the file to the RichTextBox
        rtb.Selection.Text = contents;
        btnReset.IsEnabled = true;

An instance is created of type OpenFileDialog and the filter is set to limit the choice to only text files. The ShowDialog() method displays the dialog box. When the user has selected a file through this dialog, the contents of this file will be read using the StreamReader class and displayed in the RichTextBox control. Add the following code for the Reset button to reset the contents of the RichTextBox and TextBox.

private void btnReset_Click(object sender, RoutedEventArgs e)
    txtFile.Text = "";

Save, build, and execute the application.


The RichTextBox control in Silverlight is a powerful content control, and can be manipulated in a variety of ways through XAML as well as code. You can display richly formatted text in it, and include hyperlinks, images, and the like. You can also add file contents to it at runtime.


  • 2nd August, 2010: Initial version.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mamta D
India India
Mamta has been working with .NET technologies for quite some years. Enthusiastic about Silverlight and WPF, she hopes to explore more of these and share her knowledge with others.

You may also be interested in...

Comments and Discussions

QuestionLoad rtf file in RichTextBox Pin
Member 947244716-May-13 2:58
memberMember 947244716-May-13 2:58 
GeneralMy vote of 5 Pin
Farhan Ghumra12-Jul-12 21:35
memberFarhan Ghumra12-Jul-12 21:35 
GeneralMy vote of 5 Pin
Uday Kumar B R14-Jan-12 23:16
memberUday Kumar B R14-Jan-12 23:16 
Questionhow to read the content of rich text box and displaying in textbox? Pin
zedray29-Dec-11 5:17
groupzedray29-Dec-11 5:17 
GeneralMy vote of 3 Pin
Ali Taghvajou28-Aug-11 16:37
memberAli Taghvajou28-Aug-11 16:37 
QuestionNice article! Pin
Noozyxw1-Aug-11 22:17
memberNoozyxw1-Aug-11 22:17 
General[My vote of 1] Doesn't Work Pin
John Simmons / outlaw programmer22-Feb-11 5:04
mvpJohn Simmons / outlaw programmer22-Feb-11 5:04 
GeneralRe: [My vote of 1] Doesn't Work Pin
mamta_m_d22-Feb-11 16:07
membermamta_m_d22-Feb-11 16:07 
General[My vote of 1] Not very good Pin
Member 456543322-Dec-10 23:54
memberMember 456543322-Dec-10 23:54 
GeneralRe: [My vote of 1] Not very good Pin
mamta_m_d23-Dec-10 1:11
membermamta_m_d23-Dec-10 1:11 
GeneralRe: [My vote of 1] Not very good Pin
Member 456543323-Dec-10 2:06
memberMember 456543323-Dec-10 2:06 
GeneralMy vote of 2 Pin
Mycroft Holmes30-Oct-10 0:13
mvpMycroft Holmes30-Oct-10 0:13 
GeneralRe: My vote of 2 Pin
mamta_m_d10-Nov-10 5:44
membermamta_m_d10-Nov-10 5:44 
GeneralMy vote of 5 Pin
Member 23219488-Oct-10 6:51
memberMember 23219488-Oct-10 6:51 
GeneralRe: My vote of 5 Pin
mamta_m_d10-Nov-10 5:42
membermamta_m_d10-Nov-10 5:42 
GeneralImplement Ctrl+F Pin
AndrusM3-Oct-10 4:05
memberAndrusM3-Oct-10 4:05 
GeneralMy vote of 5 Pin
defwebserver25-Sep-10 10:22
memberdefwebserver25-Sep-10 10:22 
GeneralRe: My vote of 5 Pin
mamta_m_d26-Sep-10 21:56
membermamta_m_d26-Sep-10 21:56 
GeneralMy vote of 1 Pin
Peter Weissbrod2-Sep-10 4:14
memberPeter Weissbrod2-Sep-10 4:14 
GeneralRe: My vote of 1 Pin
mamta_m_d3-Sep-10 1:31
membermamta_m_d3-Sep-10 1:31 
GeneralRe: My vote of 1 Pin
Member 80002388-Dec-13 9:09
memberMember 80002388-Dec-13 9:09 
GeneralMy vote of 4 Pin
defwebserver9-Aug-10 12:06
memberdefwebserver9-Aug-10 12:06 
GeneralRe: My vote of 4 Pin
mamta_m_d11-Aug-10 17:18
membermamta_m_d11-Aug-10 17:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151002.1 | Last Updated 24 Sep 2010
Article Copyright 2010 by Mamta D
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid