Reader Level:
TUTORIAL

WPF RichTextBox

Posted by Mahesh Chand Tutorials | WPF September 08, 2008
This tutorial shows you how to create and use a RichTextBox control available in Windows Presentation Foundation (WPF) and XAML.
  • 2
  • 0
  • 172173
Download Files:
 

Introduction

The RichTextBox control allows you to view and edit text, paragraph, images, tables, other rich text format contents.

 

The RichTextBox tag represents a RichTextBox control in XAML.

 

<RichTextBox></RichTextBox>

 

The Width and Height properties represent the width and the height of a RichTextBox.  The Name property represents the name of the control, which is a unique identifier of a control. The Margin property tells the location of a RichTextBox on the parent control. The HorizontalAlignment and VerticalAlignment properties are used to set horizontal and vertical alignments.

 

The following code snippet sets the name, height, and width of a RichTextBox control.  The code also sets horizontal alignment to left and vertical alignment to top.

 

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"

                 VerticalAlignment="Top" Width="500" Height="300" />

 

Displaying and Edit Text

A RichTextBox control hosts a collection of RichTextBoxItem. The following code snippet adds items to a RichTextBox control.

<RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left"

             VerticalAlignment="Top" Width="500" Height="300">

    <FlowDocument>

        <Paragraph>

            I am a flow document. Would you like to edit me?

            <Bold>Go ahead.</Bold>               

        </Paragraph>

     

        <Paragraph Foreground="Blue">         

            I am blue I am blue I am blue. 

        </Paragraph>

    </FlowDocument>       

</RichTextBox>

The above code generates Figure 1 where you can start editing text right away.

 

RTFImg1.jpg

Figure 1. RichTextBox with editable text

Creating and Using RichTectBox Dynamically 

In the previous section, we saw how to create and use RichTextBox in XAML. WPF provides RichTextBox class that represents a RichTextBox control. In this section, we will see how to use this class to create and use a RichTextBox control dynamically.

The code listed in Listing 1 creates a FlowDocument, adds a paragraph to the flow document and sets the Document property of the RichTextBox as FlowDocument.

private void CreateAndLoadRichTextBox()

{

    // Create a FlowDocument

    FlowDocument mcFlowDoc = new FlowDocument();

 

    // Create a paragraph with text

    Paragraph para = new Paragraph();

    para.Inlines.Add(new Run("I am a flow document. Would you like to edit me? "));

    para.Inlines.Add(new Bold(new Run("Go ahead.")));

 

    // Add the paragraph to blocks of paragraph

    mcFlowDoc.Blocks.Add(para);

 

    // Create RichTextBox, set its hegith and width

    RichTextBox mcRTB = new RichTextBox();

    mcRTB.Width = 560;

    mcRTB.Height = 280;

 

    // Set contents

    mcRTB.Document = mcFlowDoc;

 

    // Add RichTextbox to the container

    ContainerPanel.Children.Add(mcRTB);    

}

Listing 1.

The output of Listing 1 generates Figure 2.

RTFImg2.jpg

Figure 2

Enable Spelling Check

RichTextBox control comes with spelling check functionality out-of-box. By setting SpellCheck.IsEnabled property to true enables spell checking in a RichTextBox. 

SpellCheck.IsEnabled="True"

You can set this in code as following:

mcRTB.SpellCheck.IsEnabled = true;

Now if you type some text, the wrong word would be underlined with red color.

Loading a Document in RichTextBox

We are going to open a text file on a menu item click event handler.

private void OpenMenuItem_Click(object sender, RoutedEventArgs e)

{

    OpenFileDialog dlg = new OpenFileDialog();

    dlg.InitialDirectory = "c:\\";

    dlg.Filter = "Text files (*.txt)|*.txt|All Files (*.*)|*.*";

    dlg.RestoreDirectory = true;

    if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)

    {

 

        LoadTextDocument(dlg.FileName);

    }

}

 

On this menu item click event handler, we call a method called LostTextDocument by passing the text file name. In this method, we read the text file into a FileStream object and load this FileStream into a TextRange object, which is range of the RichTextBox control. 

 

private void LoadTextDocument(string fileName)

{

    TextRange range;

    System.IO.FileStream fStream;

    if (System.IO.File.Exists(fileName))

    {

        range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);

        fStream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);

        range.Load(fStream, System.Windows.DataFormats.Text );

        fStream.Close();

    }

}

 

 

Converting RichTextBox Contents to a String

 

There is no direct method or property in RichTextBox that can extract the document or contents of a RichTextBox to a string. To convert the contents to a string, we first need to read the contents of a RichTextBox in a TextRange object and use TextRange.Text property to convert it to a string.

The following code snippet reads a RichTextBox contents from start to end and converts to a string.

string ConvertRichTextBoxContentsToString(RichTextBox rtb)

{

    TextRange textRange = new TextRange(rtb.Document.ContentStart,

        rtb.Document.ContentEnd);

    return textRange.Text;

}

Summary

In this article, I discussed how to create and use a RichTextBox control available in WPF.  We saw how we can load a text file contents to a RichTextBox control dynamically.

 



 

COMMENT USING

Trending up