0
votes

How can I create a WPF control (similar to a TextBlock) so that any overflowing text is faded out to transparent rather than simply clipping or wrapping?

I need to keep my control fixed-width, so expanding the width of the control to fit the text is not an option. I also do not want to make the text font smaller.

3

3 Answers

1
votes

Not quite sure exactly what you are trying to achieve, but you could do something like this:

    <TextBlock Text="Some long text here that should fade out">
        <TextBlock.Foreground>
            <LinearGradientBrush>
                <GradientStop Offset="0" Color="Black"/>
                <GradientStop Offset="0.7" Color="Black"/>
                <GradientStop Offset="1" Color="Transparent"/>
            </LinearGradientBrush>
        </TextBlock.Foreground>
    </TextBlock>

But your control still needs to be wide enough to accommodate all the text for it to display.

1
votes
<TextBlock Text="fgdfgfdgfddgfdgdfgfdgfdgd" Width="129" TextWrapping="NoWrap">
        <TextBlock.Foreground>
            <LinearGradientBrush EndPoint="0.661,0.399" StartPoint="0.008,0.496">
                <GradientStop Color="Black" Offset="0"/>                    
                <GradientStop Color="#7F000000" Offset="0.803"/>
                <GradientStop Color="#4C0A0909" Offset="0.95"/>
                <GradientStop Color="#BF000000" Offset="0.729"/>
                <GradientStop Color="#F8000000" Offset="0.699"/>
            </LinearGradientBrush>
        </TextBlock.Foreground>
    </TextBlock>            

The trick on the gradient is that even though all colors are all based off black, The fade is achieved through opacity of each gradient by playing with A part of RGBA, in pseudo-code:

GradientStop Color="Black" A=100%               
GradientStop Color="Black" A=97%  Offset="0.803"
GradientStop Color="Black" A=75%  Offset="0.95"
GradientStop Color="Black" A=80%  Offset="0.729"
GradientStop Color="Black" A=30%  Offset="0.699"
0
votes

Thanks guys, but I found the answer I needed on MSDN.