简体   繁体   English

如何使圆形边框和背景颜色完全适合 TextBlock 中的文本范围?

[英]How to make a rounded Border and Background colour exactly fit the text extents in a TextBlock?

I've got the following XAML:我有以下 XAML:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="140"/>
        <ColumnDefinition Width="60"/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="{Binding Level}"/>
</Grid>

Level is basically a log level ( Verbose , Information , Warning , Error ). Level基本上是一个日志级别( VerboseInformationWarningError )。

First I would like to add a background colour but only to the text itself.首先,我想添加背景颜色,但仅限于文本本身。

If I do <TextBlock Text="{Binding Level}" Background="Yellow"/> then I end up with something like this:如果我这样做<TextBlock Text="{Binding Level}" Background="Yellow"/>那么我最终会得到这样的结果:

Verbose

I can workaround that by doing the following:我可以通过执行以下操作来解决此问题:

<TextBlock>
    <Run Text="{Binding Level}" Background="Yellow"/>
</TextBlock>

And now I correctly end up with:现在我正确地结束了:

Verbose

But now I would like to round the corners of just the text itself, and that... I can't find a way to do and would appreciate some help with.但现在我想绕过文本本身的角落,而且……我找不到办法,希望能得到一些帮助。

I've tried adding a Border to the TextBlock but that creates a border around the whole TextBlock , not just the text inside it.我尝试向TextBlock添加一个Border ,但这会在整个TextBlock周围创建一个边框,而不仅仅是其中的文本。

If you set an HorizontalAlignment and VerticalAlignment on a FrameworkElement like a Border or TextBlock , it will prevent it from stretching to its parent size (which is the default behavior ).如果您在FrameworkElement上设置HorizontalAlignmentVerticalAlignment ,例如BorderTextBlock ,它将阻止它拉伸到其父大小(这是默认行为)。

You can write the following XAML:您可以编写以下 XAML:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="140"/>
        <ColumnDefinition Width="60"/>
    </Grid.ColumnDefinitions>
    <Border Background="Yellow" CornerRadius="5" HorizontalAlignment="Left" VerticalAlignment="Top">
        <TextBlock Text="Hello"/>
    </Border>
</Grid>

And the Border only takes the space needed to fit its child TextBlock .并且Border只占用适合其子TextBlock所需的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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