How to change TextDecoration color in WPF TextBlock?
Asked Answered
E

2

9

I am changing the color of the TextDecoration this way:

<Grid Background="{x:Null}"
      Margin="10,0,10,0">
    <TextBlock Text="{Binding Value}"
               VerticalAlignment="Center"
               HorizontalAlignment="Center"
               Style="{StaticResource SWMRegularTextBlockStyle}"
               Margin="0"
               FontSize="{DynamicResource RegularFontSize}"
               x:Name="tb" />
        <Line VerticalAlignment="Center"
              HorizontalAlignment="Center"
              Visibility="{Binding InStock, Converter={StaticResource ReverseBooleanToVisiblity}}"
              Stroke="Red"
              Margin="0"
              StrokeThickness="2"
              X1="1"
              Stretch="Fill"
              Width="{Binding ActualWidth, ElementName=tb, UpdateSourceTrigger=PropertyChanged}" />
</Grid>

But when Text has two lines it fails. Please help me to change the color of TextDecoration. Thanks in advance.

NOTE: I want TextBlock foreground and strike-through line in different colors.

Estreat answered 15/9, 2015 at 13:20 Comment(0)
N
22

I think this is what you are looking for.

<TextBlock Text="{Binding Value}" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource  SWMRegularTextBlockStyle}" Margin="0" FontSize="{DynamicResource RegularFontSize}" x:Name="tb" >
   <TextBlock.TextDecorations>
        <TextDecoration Location="Strikethrough">
            <TextDecoration.Pen>
                <Pen Brush="Red" />
            </TextDecoration.Pen>
        </TextDecoration>
    </TextBlock.TextDecorations>
</TextBlock>
Novitiate answered 15/9, 2015 at 14:53 Comment(1)
Exactly what I just searched for.Maid
K
3

The problem you have is that you're overlaying a line on the text. When the text wraps you need to create another line which is not going to be easy.

You can solve this by not using the line at all but instead using a specific pen for the TextDecoration of the strikethrough in the code behind.

Answer found here

    private void WindowLoaded(object sender, EventArgs e)
    {
        // Fill the overline decoration with a solid color brush.
        TextDecorationCollection myCollection = new TextDecorationCollection();
        TextDecoration myStrikeThrough = new TextDecoration();
        myStrikeThrough.Location = TextDecorationLocation.Strikethrough;

        // Set the solid color brush.
        myStrikeThrough.Pen = new Pen(Brushes.Red, 2);
        myStrikeThrough.PenThicknessUnit = TextDecorationUnit.FontRecommended;

        // Set the underline decoration to the text block.
        myCollection.Add(myStrikeThrough);
        tb.TextDecorations = myCollection;
    }

And then simplify your XAML. Remove the Line control, and add Loaded="WindowLoaded" to your Window

Kimbell answered 15/9, 2015 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.