Charles Petzold

RichTextBox Selections

September 24, 2005
New York City

My first two days of good solid work on the book were Wednesday and Friday. (Thursday I had to review pages for Programming Microsoft Windows Forms, and today I fulfilled my civic duty by journeying to Washington D.C. for a modest gathering on the Ellipse.)

On Wednesday I began by writing a short program to print the Control class hierarchy, and then I decided that a good way to learn a bunch of stuff would be to write a WordPad clone using the new RichTextBox. The WPF version of this control doesn't deal with RTF files like the Win32 and WinForms versions. It maintains a document in the form of a FlowDocument object, which (of course) has an XML representation for storage.

I was really stumped for awhile on how to programmatically format a block of text selected by the user. The RichTextBox has a property named Selection of type TextRange, and TextRange turns out to be two TextPointer objects, but beyond that, there seemed no clear way to set the formatting of the selection other than to get down and dirty with the components of the FlowDocument.

After exhausting just about every other possibility, I examined the innocently named ApplyPropertyValue method of TextRange, and that was it. The first argument is an object of type DependencyProperty (which are static fields), and the second argument is defined as object, but it's an object of the type of the property associated with the DependencyProperty. The syntax looks like this:

txtbox.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, new FontFamily("Times New Roman"));


 txtbox.Selection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Subscript);


 txtbox.Selection.ApplyPropertyValue(FlowDocument.FontStyleProperty, FontStyles.Italic);

This indicates some of the importance (and strangeness) of dependency properties in WPF. The FontFamily, BaselineAlignment, and FontStyle properties are defined in three different classes, but they can all be set for a particular selection using the same method.

Having a good explanation of dependency properties in the book will be crucial, of course, but that will need to happen long before RichTextBox is discussed. The goal will be to find the ideal example and provide a much better explanation than the incomprehensible one in the beta WPF docs.