Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » WPF » WPF RichTextBox

WPF RichTextBox

This tutorial shows you how to create and use a RichTextBox control available in Windows Presentation Foundation (WPF) and XAML.

Author Rank :
Page Views : 82549
Downloads : 1025
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WPF RichTextBoxTutorial.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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 Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Tooltip by atul On October 15, 2008
Hi Mahesh how to provide different tooltip for each word in Richtextbox?
Reply | Email | Modify 
Re: Tooltip by Mahesh On April 7, 2009
Hmm .. I really am not sure. If it's a fixed label type text, you probably can load each word in a textblock control and have a tooltip on it.
Reply | Email | Modify 
WPF richtextbox Load file by Sumit On September 22, 2009

Hi,
I m getting double spacing between lines when i m trying to load the file  in WPF richtextbox but the file(.txt) is having only single spacing.

Regards,
Sumit

Reply | Email | Modify 
How to embed XAML file ? by rakesh On March 1, 2010
Hi,

I am doing a small project, practically learning WPF and C#.
My project is to make the UI editable with out using VS2008.
I tried your example to get the text of the xaml file to load into Rich Text Box.
I want to load a XAML file with all its GUI intact. 

Is there a way I can do this ??
Which container should I use in order to achieve my goal ??

Thanks
Rakesh D.

Reply | Email | Modify 
hekp on richtextbox formatting by Ashwin On April 8, 2010
0 vote down star

i am making a project for bulk emailing . In this I have added a richtext box . I want users to enter the email message body in it and want to give them the ability to format .Richtext box should be able to make the content bold,italics, underline , align it right left and center , increase font , decrease font,change color, change the font like Times New Roman depending on the click of the button. Help me how should i go about it. also let me know which references i should add to my project.its urgent guys . please help

Reply | Email | Modify 
adding a image tag to richtext box by Ashwin On April 11, 2010
i want to add an image tag to the richtextbox dynamically after the user has completed entering the text. this image tag will be appended everytime to the richtext box . ex:
<img src='websiteaddress/api/filename.php?userid=username&emailid=email_id&emsgid=eno'/>  where username,email_id & eno are string variables in c#.net.
how should i go about it . plz help its urgent..
Reply | Email | Modify 
Need rtf solution by K On June 8, 2011
I want to load rtf file with images in rich text box of asp.net The rtf file are load with images but the image position in change in the editor.. How can i load the rtf file with images with its original position?? Pls Relpy... Thnks..
Reply | Email | Modify 
Nice Article by Vineet Kumar On November 21, 2011
Nice......
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.