简体   繁体   中英

wpf textblock - set background color behind text only?

when I set the background color on a textblock, it colors the fill rectangle of the textblock. If I have a multi-line textblock, in which the lines are normally unequal length, this shows empty spaces past the end of the shorter lines. This is fine, but is there a way I could set background color only behind the text lines themselves so this empty space is not created?

I'm not at a Windows machine so can't test this myself. The first thing I would try would be to style the Run class rather than TextBlock :

<Style TargetType="Run">
    <Setter Property="Background" Value="Blue"/>
</Style>

...

<TextBlock TextWrapping="Wrap">
    Lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
</TextBlock>

I would do this on the assumption that TextBlock creates multiple Run instances when it has to wrap lines.

I think the easiest way is to put the TextBlock inside a border with BorderThickness=0 and set the background of the border. The border will expand with your textblock but won't take up extra space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM