views:

129

answers:

3

For instance, if I have a TextBlock:

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

I want the first 10% of this TextBlock, such that the font color should be red, and the rest should be green.

This perhaps means it would color the "Lorem ipsum dolor sit amet, consectetur adipisici", and part of the "n". Basically pixel-wise font coloring instead of character-wise.

Another important behavior is that the percentage respects the wrapping, in that if 50% of the TextBlock contents is colored, it should mean 50% of the text in reading order is colored, and not the first half of the block.

For example, this is a similar question (with correct answers), but regarding Label/TextBlocks with no wrapping: http://stackoverflow.com/questions/2394421/is-it-possible-to-seletively-color-a-label-in-silverlight

+3  A: 

I don't believe this is possible pixel-wise (at least not without measuring the text and using one of the techniques from the linked question on a line-by-line basis). It can be done character-wise using a Run object:

<TextBlock FontSize="24" TextWrapping="Wrap">
  <Run Foreground="Red">Lorem ipsum dolor sit amet, consectetur</Run>
  adipisicing elit, sed do eiusmod tempor incididunt ut labore et
  dolore magna aliqua. Ut enim ad minim veniam...
</TextBlock>

If the text is dynamic, you'd need to write code to partition the text into the two Runs (and assign them to the TextBlock.Inlines collection), but it shouldn't be too hard to encapsulate that into a custom control.

itowlson
+4  A: 

You can use Runs, to separate your text. In that sense, you can modify the background of each run, like so...

    <TextBlock>
        <Run Background="Red">
            Republican
        </Run>
        <Run Background="Blue">
            Democrat
        </Run>
    </TextBlock>
Software.Developer
+2  A: 

To my knowledge, there is no built in support for this scenario. In WPF, I expect you'd have to write your own TextFormatter. In Silverlight, you might have to do something horrible like rendering to an in-memory bitmap and using image manipulation to find the pixels to change and then drawing the bitmap on the screen. Eugh.

Alun Harford