71

I have a textblock of width say 500, but my string is just say "H" but I want to underline the whole textblock width not just under H what can I do?

Ilker Baltaci
  • 11,644
  • 6
  • 63
  • 79
user679530
  • 897
  • 1
  • 8
  • 11
  • Do you want a bottom border on the text box or do you specifically want the text underlined? – Craig Suchanec Apr 09 '11 at 00:24
  • http://stackoverflow.com/questions/552303/declaring-text-decorations-such-as-underline-strikethrough-in-a-style –  Sep 28 '11 at 08:42

4 Answers4

221

You should use the property "TextDecorations" of the TextBlock. Like that:

 <TextBlock Text="H" TextDecorations="Underline"/>
Talia H
  • 2,235
  • 2
  • 13
  • 3
  • 3
    This will underline the text but the underline will not span the entire width of the TextBlock. – Ben Gribaudo Mar 05 '12 at 19:49
  • 13
    Not really easiest if it doesn't answer the question. – MikeKulls Oct 29 '12 at 22:35
  • 7
    In terms of practicality, this is the answer most people are looking for when they google "wpf textblock underline" and get this QA as the first result. That was the case for me as well as many others if the vote count is any indicator. – Hagelt18 Jun 23 '16 at 17:08
  • Also works with WinUI3 – 27k1 Aug 05 '23 at 09:23
24

Just to add my 2 cents, The same effect as Talia's answer can be achieved at runtime through this code:

YourTextBlock.TextDecorations = System.Windows.TextDecorations.Underline;

For some reason VS2010 doesn't show Intellisense for the RHS, but it compiles and runs correctly.

dotNET
  • 33,414
  • 24
  • 162
  • 251
15
        <TextBlock VerticalAlignment="Bottom" 
                   HorizontalAlignment="Center" 
                   Margin="40" 
                   Height="40" 
                   FontSize="16" 
                   Tapped="TextBlock_Tapped"
                   Text="Text"
                   Foreground="{StaticResource LightBlue}">
            <Underline>
                <Run Text="Text"/>
            </Underline>
        </TextBlock>
Ilker Baltaci
  • 11,644
  • 6
  • 63
  • 79
  • Man, that is great! – Mikhail T. Jan 08 '17 at 21:26
  • @IlkerBaltaci My upvote. This solution is more flexible since it gives you control over how much text you want underlined. You can break the text with `` tag and then surround only the text part that you want underlined with . **Example**: ` `This solution helped me a lot for my requirements. – nam Nov 16 '20 at 17:24
1

Your best bet would probably be to use a Rectangle positioned immediately below the text block, whose width is always the width of the text block. Like this:

<DockPanel LastChildFill="False">
    <TextBlock DockPanel.Dock="Top" x:Name="blockToUnderline" Text="H" Width="76" />
    <Rectangle DockPanel.Dock="Top" Fill="Black" Height=1 Width="{Binding ElementName=blockToUnderline, Path=ActualWidth}" />
</DockPanel>
thefellow3j
  • 104
  • 4