question

SteveWood-4261 avatar image
0 Votes"
SteveWood-4261 asked ·

How to set background color on TextBlock

How can the background color on a TextBlock control be changed?

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

macintoshpro avatar image
1 Vote"
macintoshpro answered ·

TextBlock don't have background property, but you can put it inside a Grid and set background for grid
3391-msqa.png



msqa.png (6.0 KiB)
· 1 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@macintoshpro note that you do no longer need to insert an image to show HTML code. We now support HTML code in posts: HTML code in your posts


1 Vote 1 · ·
SteveWood-4261 avatar image
0 Votes"
SteveWood-4261 answered ·

Ah...right...a child control inherits some of the visual attributes of the parent. So, I can put the TextBlock in one of the panels such as a Canvas or ItemsPanel and set the background on the panel. Sure is humongous overhead just to set the background of a control.

· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RoyLi-MSFT avatar image
0 Votes"
RoyLi-MSFT answered ·

Hello,

TextBlock derives from FrameworkElement and there is no background property for FrameworkElement. So there is no background property for the Textblock class.
Generally, we will provide the background effect with an additional element looks like a container for the TextBlock. For example, we could use Border or Grid like @macintoshpro mentioned in his reply.

If you are using border, it looks like this:

 <Border Background="Red">
   <TextBlock/>
 </Border>


Thank you.



· 2 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I decided on using a border, but I'm doing it at runtime so it looks like this:

 Border thisBorder = new Border();
 TextBlock thisTextBlock = new TextBlock();
 thisBorder.Child = thisTextBlock;

A Border control is the way to go if we need a container for a single control because a Border can only have one Child; thus, doesn't have the overhead of the Children property which is a list of UIElements that the other containers have.

0 Votes 0 · ·

Sure, glad to hear that it meets your requirements. If this helps you, please accept it as answer. It might help other people with the same problem.

0 Votes 0 · ·