Edward Tanguay
Edward Tanguay

Reputation: 193442

How to change the background color of a Textblock in Silverlight?

I want a textblock that has blue text on a yellow background. I can set the blue text with the "Foreground" attribute. But "Background" doesn't work (that would be too easy I guess).

So what is the best way to do this, wrap it in a Rectangle or Canvas that has a background color?

And, is there anything we should know about Silverlight to understand why they didn't include a Background attribute for many of the elements on which you would often want to set the background color?

e.g. this gives the error "The property Background was not found in type Textblock":

<TextBlock 
    Foreground="Blue" 
    Background="Yellow"
        Height="20" 
    HorizontalAlignment="Stretch" 
    Margin="0"
    Test="this is a test"/>

Upvotes: 28

Views: 50323

Answers (4)

igor_bugaenko
igor_bugaenko

Reputation: 109

For me worked next:

<Border Background="GreenYellow">
    <TextBlock Text="sdfs" Height="60" Width="200"  />
</Border>

Upvotes: 10

Braulio
Braulio

Reputation: 1728

Just if somebody founds this thread googling or binging...

If you need background for that use the label control it's in the toolkit since version 3, and I guess on version 4 it's already included in the core.

Refer Label Control in Silverlight

Upvotes: 5

Sorskoot
Sorskoot

Reputation: 10310

TextBlock is derived from FrameworkElement. TextBox is derived from Control, which is derived from FrameworkElement. The Background color property is placed in Control.

In WPF the TextBlock has a Background Property of it's own.

The best way to add a color behind your text is to place the text inside a container like a Border or a Grid. Something like:

<Grid  Background="Yellow" >  
    <TextBlock Foreground="Blue"
               Height="20"
               HorizontalAlignment="Stretch"
               Margin="0" 
               Text="this is a test"/> 
</Grid>

Upvotes: 44

Steven Robbins
Steven Robbins

Reputation: 26599

It's not in Silverlight for some reason, although it is in WPF. Just wrap a Border round it (it will resize to the content automatically).

Upvotes: 6

Related Questions