Text and the User Interface

As we saw in the Introduction and Chapter 13, a WPF application's appearance is defined by its visual tree—a tree of objects derived from the Visual base class. Text must fit into this model, but we have several different options for adding text into the visual tree depending on the balance we require between control and ease of use.

The lowest level at which we can work with text is to use the visual layer drawing techniques introduced in Chapter 13. The next level up is to use the Glyphs class, which offers a similar level of control as visual layer programming, but packaged into a framework element. This enables it to be used from markup and to provide the usual framework-level features, such as event support and participation in layout. The GlyphRunDrawing class offers similar features, but you can incorporate it into a drawing. Finally, you can use the text object model in conjunction with one of the elements that knows how to render this form of text, such as TextBlock or FlowDocumentReader. TextBlock is the most widely used, as it offers a good balance between simplicity and flexibility.

TextBlock

The TextBlock element is usually the best choice for presenting simple text. It can handle both plain text and formatted text, and can cope easily with anything from a single character to a few paragraphs. Example 14-9 shows TextBlock at its simplest.

Example 14-9. Simple TextBlock

<TextBlock Text="Some text" />

Because TextBlock derives from FrameworkElement ...

Get Programming WPF, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.