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?
WPF TextBlock Underline
Asked Answered
Do you want a bottom border on the text box or do you specifically want the text underlined? –
Castile
#552803 –
Tsarina
You should use the property "TextDecorations" of the TextBlock. Like that:
<TextBlock Text="H" TextDecorations="Underline"/>
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 WinUI3 –
Rifling
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.
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 methods –
Swenson
<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>
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 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>
© 2022 - 2024 — McMap. All rights reserved.