Using WPF RichTextBox using C# and XAML

Introduction

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

The <RichTextBox> element of XAML represents a WPF RichTextBox control.

  1. <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.

  1. <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 elements. Each item can be any flow content element. The following code snippet adds several items to a RichTextBox control.

  1. <RichTextBox Margin="10,10,0,13" Name="RichTextBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="300">  
  2.     <FlowDocument>  
  3.         <Paragraph> I am a flow document. Would you like to edit me? <Bold>Go ahead.</Bold>  
  4.         </Paragraph>  
  5.         <Paragraph Foreground="Blue"> I am blue I am blue I am blue. </Paragraph>  
  6.     </FlowDocument>  
  7. </RichTextBox>  

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

WPF RichTextBox control
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. We can also create and use a RichTextBox control dynamically using C#.

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.

  1. privatevoid CreateAndLoadRichTextBox() {  
  2.     // Create a FlowDocument  
  3.     FlowDocument mcFlowDoc = newFlowDocument();  
  4.     // Create a paragraph with text  
  5.     Paragraph para = newParagraph();  
  6.     para.Inlines.Add(newRun("I am a flow document. Would you like to edit me? "));  
  7.     para.Inlines.Add(newBold(newRun("Go ahead.")));  
  8.     // Add the paragraph to blocks of paragraph  
  9.     mcFlowDoc.Blocks.Add(para);  
  10.     // Create RichTextBox, set its hegith and width  
  11.     RichTextBox mcRTB = newRichTextBox();  
  12.     mcRTB.Width = 560;  
  13.     mcRTB.Height = 280;  
  14.     // Set contents  
  15.     mcRTB.Document = mcFlowDoc;  
  16.     // Add RichTextbox to the container  
  17.     ContainerPanel.Children.Add(mcRTB);  
  18. }  

Listing 1.

The output of Listing 1 generates Figure 2.

WPF RichTextBox
Figure 2

Enable Spelling Check in RichTextBox

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

SpellCheck.IsEnabled="True"

You can set this in code as following,

  1. mcRTB.SpellCheck.IsEnabled = true;  

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

Loading a Document in RichTextBox

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

  1. privatevoid OpenMenuItem_Click(object sender, RoutedEventArgs e) {  
  2.     OpenFileDialog dlg = newOpenFileDialog();  
  3.     dlg.InitialDirectory = "c:\\";  
  4.     dlg.Filter = "Text files (*.txt)|*.txt|All Files (*.*)|*.*";  
  5.     dlg.RestoreDirectory = true;  
  6.     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) {  
  7.         LoadTextDocument(dlg.FileName);  
  8.     }  

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.

  1. privatevoid LoadTextDocument(string fileName) {  
  2.     TextRange range;  
  3.     System.IO.FileStream fStream;  
  4.     if (System.IO.File.Exists(fileName)) {  
  5.         range = newTextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);  
  6.         fStream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);  
  7.         range.Load(fStream, System.Windows.DataFormats.Text);  
  8.         fStream.Close();  
  9.     }  
  10. }  

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.

  1. string ConvertRichTextBoxContentsToString(RichTextBox rtb) {  
  2.     TextRange textRange = newTextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);  
  3.     return textRange.Text;  
  4. }  

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.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.