1
votes

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

1
are you talking about TextBlock or TextBox??Justin XL
+1 @Xin I assume TextBox because TextBlock doesn't have a Background property.Kirk Broadhurst
Hummm. I see where my problem is.. I used a textbox in the resource editor while I was attempting to use a TextBlock in code.. Duh..!jyavenard

1 Answers

5
votes

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.