WPF TextBlock Underline

C#Visual StudioWindows PhoneTextblockUnderline

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

 <TextBlock Text="H" TextDecorations="Underline"/>

Solution 2 - C#

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.

Solution 3 - C#

        <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>

Solution 4 - C#

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser679530View Question on Stackoverflow
Solution 1 - C#Talia HView Answer on Stackoverflow
Solution 2 - C#dotNETView Answer on Stackoverflow
Solution 3 - C#Ilker BaltaciView Answer on Stackoverflow
Solution 4 - C#thefellow3jView Answer on Stackoverflow