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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
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">
</RichTextBox>
</Grid>
</UserControl>
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"/>
<LineBreak/>
<InlineUIContainer>
<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" />
</InlineUIContainer>
<LineBreak/>
<LineBreak/>
<Hyperlink NavigateUri="http://en.wikipedia.org/wiki/Macro_photography">
Click here to read about macro photography</Hyperlink>
</Paragraph>
</RichTextBox>
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:
private void btnMore_Click(object sender, RoutedEventArgs e)
{
MainPage ps = this;
ps.Navigate(new Page2());
}
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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Navigation"
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" />
</Grid>
</navigation:Page>
This will create a RichTextBox, Button, TextBlock, and TextBox on the page. Add the following code to the code-behind (Page2.xaml.cs):
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)
{
OpenFileDialog odlg = new OpenFileDialog();
odlg.Filter = "Text files|*.txt";
odlg.Multiselect = false;
string contents = null;
if ((bool)odlg.ShowDialog())
{
txtFile.Text = odlg.File.Name;
StreamReader reader = new StreamReader(odlg.File.OpenRead());
while (!reader.EndOfStream)
{
contents = reader.ReadToEnd();
}
reader.Close();
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 = "";
rtb.Blocks.Clear();
}
Save, build, and execute the application.
Conclusion
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.
History
- 2nd August, 2010: Initial version.