Search code examples
wpfxamlcolorstextblock

Foreground colour of textblock based on position of part of the letter


A Mars bar challenge at work is that using Xaml only, make the following text of a text block gray by default. But, from half way through the letter "e" and to half way to last character "1" make the colour red.

The text is "Item 1". So, "I" and "t" all gray, but the first half of "e" red, all of "m" red and then half of "1" red and the last half of "1" gray.

I have no idea about this one.


Solution

  • Were you thinking about something like this?

    <TextBlock FontSize="72">
        <Run Foreground="Gray" Text="It" /><Run Text="e">
            <Run.Foreground>
                <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                    <GradientStop Color="Gray" Offset="0"/>
                    <GradientStop Color="Gray" Offset="0.5" />
                    <GradientStop Color="Red" Offset="0.5" />
                    <GradientStop Color="Red" Offset="1" />
                </LinearGradientBrush>
            </Run.Foreground>
        </Run><Run Text="m" Foreground="Red" /><Run Text=" 1">
            <Run.Foreground>
                <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                    <GradientStop Color="Red" Offset="0"/>
                    <GradientStop Color="Red" Offset="0.5" />
                    <GradientStop Color="Gray" Offset="0.5" />
                    <GradientStop Color="Gray" Offset="1" />
                </LinearGradientBrush>
            </Run.Foreground>
        </Run>
    </TextBlock>
    

    Result:

    result