0

I've got the following 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).

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:

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.

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
Aterisk
  • 9
  • 1
  • 2
    What about setting an ``HorizontalAlignment`` to your `TextBlock?` It will prevent it from stretching to its parent size (here, an oversized grid column). – Corentin Pane Nov 21 '19 at 10:09
  • 1
    You can set the width of first column to `Auto`, e.g. `` to auto width column according its content – Pavel Anikhouski Nov 21 '19 at 10:12
  • That works for the `TextBlock` itself, but if I add a `Border` and set the `Background="Yellow` to the `Border` (and also `CornerRadius="10"` or so) then it will again take up the whole grid column. – Aterisk Nov 21 '19 at 10:12
  • @PavelAnikhouski setting it to `Auto` will also cause it to potentially take up more space than what I want it to (it won't truncate values) – Aterisk Nov 21 '19 at 10:14

1 Answers1

1

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).

You can write the following 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.

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
  • 1
    Absolute correct answer, just need to wait a few minutes before accepting it xD – Aterisk Nov 21 '19 at 10:18
  • If you want to later clip the border so the background does not spill out. https://stackoverflow.com/questions/24158147/clipping-a-border-in-wpf – eran otzap Nov 21 '19 at 10:29