C# – Change background colour of TextBlock in C#

csilverlightwindows-phone-7

Currently porting an application to Windows Phone 7 I've encountered a problem that should be trivial

All I want is change the background colour of a TextBlock.
Using the WYSIWYG I can easily create a TextBlock, change the foreground and background colour.
So for a TextBlock using white text on black background I would use:

<TextBox Height="148" HorizontalAlignment="Left" Margin="106,0,0,0" Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="460" Background="Black" BorderBrush="Black" Foreground="White" />

But I need to do it in code (C#) and the Background doesn't appear to be a property of TextBlock.
How come it's something you can do using the resource editor, but not in code?

I've found various similar questions, but no definitive answer.
In Microsoft documentation (.Net), TextBlock does appear to have a Background property

Is there a way to do this in code without having to put the TextBlock inside a container (like Grid) which does have the Background property?
Thanks
JY

Best Answer

TextBlock is not inherited from Control, it doesn't have a Background property. The code you are showing is a TextBox not a TextBlock. TextBox inherites from Control and has a Background property. The simplest way is to wrap it with a Panel, or you can create a custom control for it.

Also, in silverilght sdk, you have a control called Label and it is inherited from Control. You can probably get the source code from there and implement it in your project.

Related Topic