Set superscript and subscript in formatted text in wpf

后端 未结 8 543
时光说笑
时光说笑 2020-11-27 06:37

How can I set some text as subscript/superscript in FormattedText in WPF?

相关标签:
8条回答
  • 2020-11-27 06:55

    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.

    0 讨论(0)
  • 2020-11-27 07:00

    You use Typography.Variants:

    <TextBlock>
        <Run>Normal Text</Run>
        <Run Typography.Variants="Superscript">Superscript Text</Run>
        <Run Typography.Variants="Subscript">Subscript Text</Run>
    </TextBlock>
    
    0 讨论(0)
  • 2020-11-27 07:00

    This is the only thing that worked for me. It also gives you more control over the alignment and font size.

    <TextBlock Grid.Row="17">
        3 x 3<Run FontSize="6pt" BaselineAlignment="TextTop">2</Run>)
    </TextBlock>
    
    0 讨论(0)
  • 2020-11-27 07:09

    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.

    0 讨论(0)
  • 2020-11-27 07:12

    I don't know if you need this to work with FormattedText specifically, or you mean derivations of Inline, but the following will work on Inlines, even if Typography.Variants="Superscript" fails to work.

    TextRange selection = new TextRange(document.ContentStart, document.ContentEnd);
    selection.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Superscript);
    

    Hope it helps!

    0 讨论(0)
  • 2020-11-27 07:14

    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>
    
    0 讨论(0)
提交回复
热议问题