Set superscript and subscript in formatted text in

2019-01-06 17:36发布

How can i set some text as subscript/superscript in FormattedText in wpf

8条回答
闹够了就滚
2楼-- · 2019-01-06 18:10

You use Typography.Variants:

<TextBlock>
    <Run>Normal Text</Run>
    <Run Typography.Variants="Superscript">Superscript Text</Run>
    <Run Typography.Variants="Subscript">Subscript Text</Run>
</TextBlock>
查看更多
三岁会撩人
3楼-- · 2019-01-06 18:11

It's interesting to note that for some characters (m2, m3, etc) a superscript is not needed, but the unicode character can be used. For example:

<Run Text=" m&#x00B3;" />

This would show m3.

查看更多
看我几分像从前
4楼-- · 2019-01-06 18:14

Setting for superscript works fine with the following code:

<TextBlock Text="(cm"  />
<TextBlock ><Span BaselineAlignment="Top" FontSize="8">2</Span></TextBlock>
<TextBlock Text=")" />

Setting the Baseallignment for subscript in the Span tag did not work for me. I tried the following code and it worked fine.

  <TextBlock Text="H"  />
  <TextBlock Text="2" Margin="-2,0,-2,0" TextBlock.LineHeight="3" >   
  <TextBlock Text="O" />
查看更多
在下西门庆
5楼-- · 2019-01-06 18:16

I used a layout transform, because Typography.Variants often doesn't work:

<TextBlock Text="MyAmazingProduct"/>
 <TextBlock Text="TM">
  <TextBlock.LayoutTransform>
   <!-- Typography.Variants="Superscript" didn't work -->
   <TransformGroup>
    <ScaleTransform ScaleX=".75" ScaleY=".75"/>
    <TranslateTransform Y="-5"/>
   </TransformGroup>
  </TextBlock.LayoutTransform>
 </TextBlock>
<TextBlock Text="{Binding Path=Version, StringFormat={} v{0}}"/>

The advantage of using a LayoutTransform is that it is insensitive to the fontsize. If the fontsize is changed afterwards, this superscript works where explicit FontSize setting breaks.

查看更多
聊天终结者
6楼-- · 2019-01-06 18:16

Typography.Variants works only for open type fonts. If you dont like your superscripts/subscripts going outside the height of actual text then you can use something like the following:

<StackPanel Orientation="Horizontal">
    <TextBlock FontSize="10" Margin="0,5,0,0">1</TextBlock>
    <TextBlock FontSize="30">H</TextBlock>
    <TextBlock FontSize="10" Margin="0,20,0,0">2</TextBlock>
</StackPanel>
查看更多
祖国的老花朵
7楼-- · 2019-01-06 18:19

You can use something like <TextBlock>5x<Run BaselineAlignment="Superscript">4</Run> + 4</TextBlock>.

However, as far as I know, you will have to reduce the font-size yourself.

查看更多
登录 后发表回答