April 11, 2011

Font Variations and WPF Textblocks

Over the past few months I have been working on more projects using Windows Presentation Foundation (WPF) and I have ran into numerous fun "learning experiences".  Of of these recent ones prompted me to put up a "Quick Tip" posting.  The quick tip in this posting is around 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.

  The quick brown fox emits CO2 when running

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:

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

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!

tags: .NET 4.0, WPF
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.