Click here to Skip to main content
Click here to Skip to main content

Using RichTextBox in Silverlight 4

, 24 Sep 2010 CPOL
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"
    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:

// 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" 
           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):

//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();
        }
        reader.Close();
        // 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 = "";
    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.

License

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

Share

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.

Comments and Discussions

 
QuestionLoad rtf file in RichTextBox PinmemberMember 947244716-May-13 3:58 
GeneralMy vote of 5 PinmemberFarhan Ghumra12-Jul-12 22:35 
GeneralMy vote of 5 PinmemberUday Kumar B R15-Jan-12 0:16 
Questionhow to read the content of rich text box and displaying in textbox? Pingroupzedray29-Dec-11 6:17 
GeneralMy vote of 3 PinmemberAli Taghvajou28-Aug-11 17:37 
QuestionNice article! PinmemberNoozyxw1-Aug-11 23:17 
General[My vote of 1] Doesn't Work PinmvpJohn Simmons / outlaw programmer22-Feb-11 6:04 
GeneralRe: [My vote of 1] Doesn't Work Pinmembermamta_m_d22-Feb-11 17:07 
General[My vote of 1] Not very good PinmemberMember 456543323-Dec-10 0:54 
GeneralRe: [My vote of 1] Not very good Pinmembermamta_m_d23-Dec-10 2:11 
GeneralRe: [My vote of 1] Not very good PinmemberMember 456543323-Dec-10 3:06 
GeneralMy vote of 2 PinmvpMycroft Holmes30-Oct-10 1:13 
GeneralRe: My vote of 2 Pinmembermamta_m_d10-Nov-10 6:44 
GeneralMy vote of 5 PinmemberMember 23219488-Oct-10 7:51 
Excellent example. Exactly what I needed.
GeneralRe: My vote of 5 Pinmembermamta_m_d10-Nov-10 6:42 
GeneralImplement Ctrl+F PinmemberAndrusM3-Oct-10 5:05 
GeneralMy vote of 5 Pinmemberdefwebserver25-Sep-10 11:22 
GeneralRe: My vote of 5 Pinmembermamta_m_d26-Sep-10 22:56 
GeneralMy vote of 1 PinmemberPeter Weissbrod2-Sep-10 5:14 
GeneralRe: My vote of 1 Pinmembermamta_m_d3-Sep-10 2:31 
GeneralRe: My vote of 1 PinmemberMember 80002388-Dec-13 10:09 
GeneralMy vote of 4 Pinmemberdefwebserver9-Aug-10 13:06 
GeneralRe: My vote of 4 Pinmembermamta_m_d11-Aug-10 18: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
Web03 | 2.8.141223.1 | Last Updated 24 Sep 2010
Article Copyright 2010 by Mamta D
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid