views:

32

answers:

1

I need to draw a line of text with that has a different background for part of the string (i.e. like a highlight) in WPF. The FomattedText class allows you to set various attributes for different parts of a string like bold, underline fore color etc but does not have background color. I think using TextFormatter and writing a custom TextSource will do the job but it seems like a fairly heavy weight way of doing something quite simple. Is there another way to do it?

A: 

You can do this by using a basic TextBlock with multiple Inline children and giving them separate background colors. Here is a simple example in XAML:

<TextBlock>
    <Run Background="Blue">Foo</Run>
    <Run Background="Red">Bar</Run>
</TextBlock>

Note that a ContentPresenter with no template will automatically wrap Inline objects in a TextBlock, so you can just bind the Content property of a ContentControl to a Span. See this StackOverflow question for advice on data binding to Inlines.

If you want the text to be editable by the user, then you should look at RichTextBox.

Quartermeister