BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Text Input Controls - RichTextBox

The fifty-third part of the Windows Presentation Foundation Fundamentals tutorial describes the RichTextBox control. This control permits the editing of documents with complex formatting and inserted images.

Saving a RichTextBox Document to Disk

We can now add the Save button's code To generate the data from the Document property, we need to create a TextRange object that represents all of the rich text information. TextRanges represent selections in a document. We'll create one that starts at the beginning of the document and finishes at the end. The TextRange can then be saved to a FileStream using its Save method.

private void Save_Click(object sender, RoutedEventArgs e)
{
    using (FileStream fs = new FileStream(
        FileLocation, FileMode.OpenOrCreate, FileAccess.Write))
    {
        var doc = MyRichText.Document;
        TextRange textRange = new TextRange(doc.ContentStart, doc.ContentEnd);
        textRange.Save(fs, DataFormats.Rtf);
    }
}

You can see that the format for the new file is set using the second parameter of the Save method. In this case we've stored the document as a rich text file, which can be loaded into word processor packages such as Microsoft Word. You can also save the document as XAML or plain text by choosing an alternative value from the DataFormats enumeration.

Loading a RichTextBox Document from Disk

To complete the program we need to add the code for the Load button. This is the very similar to the Save code. First we open a FileStream for the file, then use the Document property's Load method to open the file. NB: In a production environment you should add appropriate exception handling for file errors.

private void Load_Click(object sender, RoutedEventArgs e)
{
    using (FileStream fs = new FileStream(FileLocation, FileMode.Open, FileAccess.Read))
    {
        var doc = MyRichText.Document;
        TextRange textRange = new TextRange(doc.ContentStart, doc.ContentEnd);
        textRange.Load(fs, DataFormats.Rtf);
    }
}

Try running the program, editing the text and using the Save and Load buttons. If you have a suitable word processor, you can use it to open the generated rich text file.

15 March 2014