Accessing background color of textblock

micahhoover picture micahhoover · Mar 14, 2013 · Viewed 21.1k times · Source

I found this example on MSDN that shows some ways to configure a textblock:

A lot of it seems to work for me, but this part fails:

textBlock.Background = Brushes.AntiqueWhite;

The "Background" part is underscored in red and Visual Studio says: "Windows.UI.Xaml.Controls.TextBlock does not contain a definition for Background".

I am perplexed.

Is this a recent change? Or did this get removed later?

Answer

Chris W. picture Chris W. · Mar 14, 2013

If I remember right WinRT is based a lot on Silverlight, in whereas TextBlock derives from FrameworkElement and unlike in WPF, it doesn't have a Background property of its own.

A workaround would be to just provide the same effect with an additional element to act as a container and provide your background using Border or Grid with Background etc. Something like;

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

Or perhaps a Rectangle behind the TextBlock to provide the same thing if it's contained in say maybe a Grid Cell or the likes unless you wanted to set sizes on the Rectangle directly;

<Rectangle Fill="AntiqueWhite"/>
<TextBlock/>

Unfortunately I think this is your only current alternative. Hope this helps.