Display subscripts and superscripts in a WPF TextBlock in C#

[subscripts and superscripts]

The following examples show how to display subscripts and superscripts in a RichTextBox in a Windows Forms program.

In a WPF application, you can display subscripts and superscripts in a TextBlock. This example displays a Grid control that holds a vertically oriented StackPanel. The following code shows how the program defines the two TextBlock controls inside the StackPanel.

<TextBlock HorizontalAlignment="Center">
  2H<Run BaselineAlignment="Subscript" FontSize="10">2</Run>
  + O<Run BaselineAlignment="Subscript" FontSize="10">2</Run>
  = 2H<Run BaselineAlignment="Subscript" FontSize="10">2</Run>O
<TextBlock HorizontalAlignment="Center">
  3<Run BaselineAlignment="Superscript" FontSize="10">2</Run>
  + 4<Run BaselineAlignment="Superscript" FontSize="10">2</Run>
  = 5<Run BaselineAlignment="Superscript" FontSize="10">2</Run>

The TextBlock controls display the program’s two equations. You can embed a new line inside a TextBlock and display both equations in a single control if you like, but using separate controls allows the program to center them horizontally.

To make subscripts and superscripts, the TextBlock controls use Run tags. The BaselineAlignment attribute determines whether the text is a subscript or superscript. The FontSize property makes the included text smaller so it looks nicer.

That’s all there is to it. You can create a similar effect in code by manipulating the TextBlock objects, but that’s more cumbersome.

You can also set other properties in a Run. For example, you can change the font properties (name, weight, style), colors (foreground and background), text effects, tooltips, and so forth.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in fonts, formatting, wpf, XAML and tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Display subscripts and superscripts in a WPF TextBlock in C#

  1. Pingback: Use WPF code to display subscripts and superscripts in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *