Wednesday, March 9, 2011

RichTextBox

The RichTextBox is much more complex than the TextBox because it stores text that could have a variety of different character and paragraph formatting. If you're familiar with previous Windows controls similar to RichTextBox, you might naturally assume that the control stores text in the Rich Text Format (RTF), a file format that dates from the mid-1980s and which was intended to provide an interchange format among word processing programs. The WPF version of RichTextBox certainly supports RTF (and plain text as well) but it also supports an XML-based file format that is a subset of the Extensible Application Markup Language (XAML) supported by WPF.

Formatted text gets into and out of the RichTextBox through the Document property. This Document property is of type FlowDocument, and the following code creates a TextRange object that encompasses the entire document:

TextRange range = new TextRange(flow.ContentStart, flow.ContentEnd);
The TextRange class defines two methods named Load and Save. The first argument is a Stream; the second is a string describing the desired data format. For this second argument it's easiest to get those strings from static members of the DataFormats class. With the RichTextBox, you can use DataFormats.Text, DataFormats.Rtf, DataFormats.Xaml, and DataFormats.XamlPackage, which is actually a ZIP file that contains binary resources the document might require. This program is hard-coded to use DataFormats.Xaml. (The program can't load any arbitrary XAML file, however.) You may want to look at these files to get a glimpse of the format of documents under the Windows Presentation Foundation.


1 comment: