Search code examples
wpfxamltextblockunderline

How can I change the distance between text and underline in a WPF TextBlock?


I have a style guide from a designer for a button that looks like a hyperlink and I am trying to get as close to it as I can with WPF styles.

But I haven't been able to change the distance between the text and the underline. I wanted to add images for comparision but unfortunately I haven't earned enough points to do so far.

Is there a way to change the distance between text and underline?

Here is the XAML code I have so far:

<Style x:Key="LinkButton" TargetType="ButtonBase">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Cursor" Value="Hand"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ButtonBase">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="&gt; "/>
                    <TextBlock TextDecorations="Underline">
                        <ContentPresenter/>                        
                    </TextBlock>
                </StackPanel>                 
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Foreground" Value="{StaticResource LxGrayBrush}"/>
    <Setter Property="FontSize" Value="12"/>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Foreground" Value="{StaticResource LxGreenBrush}"/>
        </Trigger>
    </Style.Triggers>
</Style>

Solution

  • Use element syntax to add an instance of TextDecoration to the TextBlock.TextDecorations, then you can adjust the Location or PenOffset.

    <TextBlock>
        <TextBlock.TextDecorations>
            <TextDecoration Pen="..." Location="..."/>
        </TextBlock.TextDecorations>
    </TextBlock>
    

    (You may need to set the Pen via element syntax as well)