Text content in WPF adheres to a strict content model, with elements (hopefully) fulfilling a specific role. In practice, this is fairly familiar for developers familiar with HTML. However, there are a few things that are useful to know — one of those things is the Run element.
Here’s a simple piece of markup:
<Paragraph><Italic>Neon Bible</Italic> is the new album by the Arcade Fire.</Paragraph>
This XAML parses and displays as you would expect. Underneath the covers, the element tree created is equivalent to the following markup:
<Paragraph>
<Italic><Run Text="Neon Bible" /></Italic><Run Text=" is the new album by the Arcade Fire." />
</Paragraph>
In the land of WPF text layout, the Run element is the only element that holds actual strings of text. All other elements (Bold, Italic, etc) are ultimately formatting containers for Run elements that hold the actual text being displayed.
Knowing about these Run elements is important when you’re working programmatically with text. If you’re only doing markup, you’re (almost always) fine being blissfully unaware.
Exception to the rule
Of course, there are always exceptions to the rule — there is another element that can contain text in some cases: TextBlock. You can use TextBlock.Text, which is a DependencyProperty, to bind dynamic text. Here’s the thing to watch out for: TextBlock.Text will return the contents of TextBlock only if the content is a simple string. If you have any markup inside (such as a Bold element), TextBlock.Text returns an empty string.
2 Comments
“TextBlock.Text, which is a DynamicProperty”
You mean dependency property, don’t you?
Paul — Good catch, I fixed the typo.