Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change TextDecoration color in WPF TextBlock?

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.

like image 310
Dinesh balan Avatar asked Sep 15 '15 13:09

Dinesh balan


2 Answers

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>
like image 83
Alias Varghese Avatar answered Nov 08 '22 19:11

Alias Varghese


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

like image 33
timbo Avatar answered Nov 08 '22 18:11

timbo