Back to all posts

Font Variations and WPF Textblocks

Posted on Apr 11, 2011

Posted in category:
Development
Windows

Over the past few months I have been working on more projects using Windows Presentation Foundation (WPF) and I have run into numerous fun "learning experiences". Of these recent ones prompted me to put up a "Quick Tip" posting. The quick tip in this posting is around the formatting of custom font structures within a WPF TextBlock. Specifically around sub-scripting, super-scripting, and internal font variants.

Standard Markup

Before I get into the specifics of the tip I want to show the types of text I was working with first. Take the following example.

Basic TextBlock
<TextBlock>
  The quick brown fox emits CO2 when running
</TextBlock>

As you can be assured this would emit exactly as you see it here on the screen.

The desired result

What I was really shooting for in the end was this, The quick brown fox emits CO2 when running.

Searching through WPF documentation was not resulting in much help until I stumbled across the "Run" element that can be used inside of a textblock. Using this you can specify sub-formats for sections of your text. For example:

Complex Example
<TextBlock>
  The quick brown fox emits 
CO<Run BaselineAlignment="SubScript">2</Run> 
when running
</TextBlock>

With this, I get my desired effect. Using this you can do a lot more than sub and superscripting. You can make bold sections or many other custom combinations all within a single text block! I hope this was helpful!