Display subscripts and superscripts in a WPF TextBlock in C#

Datetime:2016-08-23 03:57:37          Topic: C#  WPF           Share

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>
<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>
</TextBlock>

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.





About List