How to add a border to the Text inside a TextBlock in WPF?
Asked Answered
P

4

7

I am kinda new to WPF, dont know if the question is weird. I wanted to know if its possible to add a border around the text inside a textBlock.

EDIT:

As per suggestion I have tried both but without much success:

<Border BorderBrush="#FF0B232F" BorderThickness="2">
   <TextBlock HorizontalAlignment="Left" Text="TextBlock" TextWrapping="Wrap" FontSize="36" FontWeight="Bold" Foreground="#FF88BCCD" OpacityMask="Black"/>      
</Border>

and

<Label BorderBrush="#FF0B232F" BorderThickness="2,2,2,2" Content="TextBlock" FontSize="36" FontWeight="Bold" Foreground="#FF88BCCD" />

Am I doing something wrong here?

Potful answered 24/2, 2011 at 13:42 Comment(3)
It's all fine with your code. What do you dislike in it?Phosphatize
His question is how to "add a border around the text INSIDE(aka content of) a textBlock"... No one answered that question. I would also like to know how to do this.Loosestrife
Look at this answer - #94150Loosestrife
P
5

In such cases I use Label or TextBlock placed in Border.

Phosphatize answered 24/2, 2011 at 13:55 Comment(0)
D
4

Both your approaches are correct, however, if you have the textblock/label inside a grid (or any other container) declared as you have, its contents will stretch. Try setting the VerticalAlignment and/or HorizontalAlignment to an appropriate setting (Top/Left, Center)..

something like this:

<Border BorderBrush="#FF0B232F" BorderThickness="2" VerticalAlignment="Top">
    <TextBlock HorizontalAlignment="Left" Text="TextBlock" TextWrapping="Wrap" FontSize="36" FontWeight="Bold" Foreground="#FF88BCCD" OpacityMask="Black"/>
</Border>
Dream answered 24/2, 2011 at 20:41 Comment(1)
Filipe is correct - if the grid/contain contains other objects then the border will effectively cover the whole grid - VerticalAlignemnt and HorizontalAlignment fixes this. Not intuitive!Bul
P
2

Assuming that you are asking for a full size TextBlock with a border overlay within the bounds of the TextBlock you could wrap it in a Grid and draw the borders over the top of the TextBlock like this...

<Grid HorizontalAlignment="Left">
    <TextBlock Text="TextBlock" TextWrapping="Wrap" FontSize="36" FontWeight="Bold" Foreground="#FF88BCCD" OpacityMask="Black" />
    <Border BorderBrush="#FF0B232F" BorderThickness="2" />
</Grid>

Because we haven't specified the grid row and column on the TextBlock and Border objects the border overlays on top of the TextBlock.

Pessimist answered 15/7, 2013 at 15:12 Comment(0)
L
0

if you just want to have a border around your textblock or any other control use :

 <Border>
      <TextBlock></TextBlock>
    </Border>

you set border properties like color ,cornerradius ,thickness,...

Linotype answered 24/2, 2011 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.