How to define stroke around background rectangle of textblock in WPF?
I would like 开发者_C百科to have some text to be inside a rectangle with stroke around this rectangle (just like property "Stroke" of the object "Rectangle" itself). But I didn't manage to find a property of the object "Textblock" which defines such a stroke.
You can place the TextBlock
inside a Border
and set the properties of the Border
to draw the rectangle around your text.
Every TextBlock
element contains one or more child Inline
elements. There is a type of Inline (InlineUIContainer
) that supports hosting a UIElement: basically, this means you can host arbitrary UI elements within a TextBlock. Flipping @GraemeF's answer on its head, you can host a Border
element inside the TextBlock, like so:
<Window x:Class="StackOverflowWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock FontSize="24" Padding="20">
<Run>Hello</Run>
<InlineUIContainer>
<Border BorderBrush="Black" BorderThickness="1" Padding="4" Margin="0,0,0,-11">
<TextBlock Text="Boxed" />
</Border>
</InlineUIContainer>
<Run>World</Run>
</TextBlock>
</Window>
This will look something like this:
You will have to experiment with the Margin on the Border element in order to get the text baselines to match up, but other than that the technique seems to work well.
精彩评论