开发者

WPF - Drawing a line of text with different background colors

开发者 https://www.devze.com 2023-01-06 03:41 出处:网络
I need to draw a line of text with that has a different background for part of the 开发者_JS百科string (i.e. like a highlight) in WPF.The FomattedText class allows you to set various attributes for di

I need to draw a line of text with that has a different background for part of the 开发者_JS百科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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消