WPF TextBlock Underline
Asked Answered
O

4

73

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?

Ojibwa answered 9/4, 2011 at 0:22 Comment(2)
Do you want a bottom border on the text box or do you specifically want the text underlined?Castile
#552803Tsarina
P
226

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

 <TextBlock Text="H" TextDecorations="Underline"/>
Phalan answered 22/2, 2012 at 7:18 Comment(4)
This will underline the text but the underline will not span the entire width of the TextBlock.Elsy
Not really easiest if it doesn't answer the question.Execratory
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.Yerga
Also works with WinUI3Rifling
S
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.

Swithbert answered 5/9, 2013 at 4:18 Comment(2)
Brilliant tip. I would've never stumbled across trying that.Camillacamille
I think it's because TextDecorations is a collection. You can use TextDecorations.Add and Clear methodsSwenson
F
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>
Fortuity answered 23/3, 2015 at 9:16 Comment(2)
Man, that is great!Pacify
@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 <Run> tag and then surround only the text part that you want underlined with <Underline>. Example: <Run Text="This is a "/> <Underline><Run Text="good "/></Underline> <Run Text="solution."/>This solution helped me a lot for my requirements.Iinden
E
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>
Eurypterid answered 2/7, 2013 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.