Use WPF code to display subscripts and superscripts in C#

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

In the post Display subscripts and superscripts in a WPF TextBlock in C# I mentioned that you could make subscripts and superscripts in WPF code but it was easier in XAML code. Juan Manuel Montes asked for an example, so here it is.

To add runs to a WPF TextBlock control, you add objects to its Inlines collection. To make subscripts and superscripts, you can add Run objects to the collection.

The program uses the following methods to make it easier to build the Run objects.

// Make a subscript run.
private Run SubscriptRun(string text, int font_size)
{
    Run run = new Run(text);
    run.FontSize = font_size;
    run.BaselineAlignment = BaselineAlignment.Subscript;
    return run;
}

// Make a superscript run.
private Run SuperscriptRun(string text, int font_size)
{
    Run run = new Run(text);
    run.FontSize = font_size;
    run.BaselineAlignment = BaselineAlignment.Superscript;
    return run;
}

The SubscriptRun method creates a Run object that holds the desired text. It then gives it a new font size and sets its BaselineAlignment property to make the text a subscript.

The SuperscriptRun method is similar except it makes the text superscripted.

The following code uses those methods to build the equations.

// Create equations with subscripts and superscripts.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    txtWater.FontSize = 16;
    txtWater.Text = "";

    txtWater.Inlines.Add("2H");
    txtWater.Inlines.Add(SubscriptRun("2", 10));
    txtWater.Inlines.Add(" + O");
    txtWater.Inlines.Add(SubscriptRun("2", 10));
    txtWater.Inlines.Add(" = 2H");
    txtWater.Inlines.Add(SubscriptRun("2", 10));
    txtWater.Inlines.Add("O");

    txtPythagoras.FontSize = 16;
    txtPythagoras.Text = "";

    txtPythagoras.Inlines.Add("3");
    txtPythagoras.Inlines.Add(SuperscriptRun("2", 10));
    txtPythagoras.Inlines.Add(" + 4");
    txtPythagoras.Inlines.Add(SuperscriptRun("2", 10));
    txtPythagoras.Inlines.Add(" = 5");
    txtPythagoras.Inlines.Add(SuperscriptRun("2", 10));
}

The code first initializes the txtWater control’s font size and clears its text. It then adds a series of runs to its Inlines collection. When it calls the collection’s Add method and passes it a string, the string is added in the control’s font and with the normal baseline alignment. The other statements add subscript runs.

The code then performs similar steps to make the txtPythagoras control display an equation that uses superscripts.

In addition to Run objects, you can add Span , LineBreak , Figure , Floater , and other elements to the Inlines collection.





About List