stackoverflow1_supersubIf it takes more than 5 minutes to write up and wasn’t easy to “bing” then its something that should be blogged for SEO purposes later in my life, as my memory fades, and I need to find things again!

Recently I was asked how to super and subscript in XAML using TextBlocks.

My personal route is to use a StackPanel that wraps individual TextBlocks.  You can then adjust the margins on the TextBlock’s to reflect whether you want them normal, superscripted or subscripted.

Yes we could do it nicer with some style resources, but this is just to illustrate the basic principles .

The code to do this is below, the rendered output is on the right.  Enjoy…

        <StackPanel Orientation="Vertical">
            <TextBlock Text="H2O3" FontSize="40" Margin="0,10"/>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="H" FontSize="40" />
                <TextBlock Text="2" FontSize="40" Margin="0,-20,0,0"/>
                <TextBlock Text="O" FontSize="40"/>
                <TextBlock Text="3" FontSize="40" Margin="0,10,0,-10"/>
            </StackPanel>
        </StackPanel>