Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting foreground of TextBlock to a LinearGradientBrush causes unwanted behavior

Tags:

c#

.net

wpf

I'm getting unwanted behavior from a TextBlock I'm using in my DataTemplate. It seems that the LinearGradientBrush that I'm using for the Foreground property is not drawing the gradient consistantly across the font for words that contain "descenders" like the lower-case 'p' in the word Vampire in the example picture.

I tried setting the LineHeight to the same as the FontSize; no change.
I tried setting the Height of the TextBlock; no change to the color, but added height to the bottom of the TextBlock.

Has anyone else dealt with this and found a solution before? I tried searching Google and StackOverflow for answers but I've come up with nothing so far.

Edit: The problem is the gradient is not applied the same to each textbox, because the descenders increase the height of the font. Look at the difference between the lower-case 'a' in the words Vampire and Brave, and you will see what I mean.

Detailed ultra-cool example image

TextBlock XAML

<TextBlock Text="{Binding Title}" FontWeight="Bold" FontStyle="Italic" 
           FontSize="20" Padding="3" LineHeight="20">
  <TextBlock.Foreground>
    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
      <GradientStopCollection>
        <GradientStop Color="White" Offset="0.2"/>
        <GradientStop Color="AliceBlue" Offset="0.4"/>
        <GradientStop Color="#6AB0EE" Offset="0.6"/>
        <GradientStop Color="DarkOrange" Offset="0.8"/>
      </GradientStopCollection>
    </LinearGradientBrush>
  </TextBlock.Foreground>
</TextBlock>
like image 420
Zack Avatar asked Sep 03 '25 03:09

Zack


1 Answers

Try to set MappingMode property like this:

<LinearGradientBrush MappingMode="Absolute" StartPoint="0,0" EndPoint="0,1" >
like image 119
Rafal Avatar answered Sep 05 '25 00:09

Rafal