Friday, June 05, 2009

Background Color of TextBlock in Silverlight 2

In a WPF application (as of .NET 3.5) you can set the background color for a text block as follows:
<TextBlock ... Background="Red" ...> </TextBlock>
Despite being correct Silverlight 2 doesn't like this XAML code. Trying to set it programmatically leads to an exception. Therefore a different solution is needed. Here is what works in my case. I use a Canvas and place a Rectangle and a TextBlock inside of that Canvas. Unless you set the ZIndex use this order so that the TextBlock is in front of the Rectangle. I use the Rectangle as the background for the TextBlock. When the TextBlock changes its size I update the size of the Rectangle accordingly. This solution is pretty simple in the end. First the XAML code:
<UserControl x:Class="Foo.LabelWithBackground"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Width="200" Height="20">
   <Canvas>
      <Rectangle Name="_labelBackground" Width="20" Height="20"
                 Fill="LightSkyBlue"/></Rectangle>
      <StackPanel>
         <TextBlock Height="20" HorizontalAlignment="Left" Name="_label"
                    VerticalAlignment="Center" Padding="4,2,4,0" 
                    Text="The Label Text" MinWidth="20"></TextBlock>
      </StackPanel>
   </Canvas>
</UserControl>
Next the C# code-behind:
public partial class LabelWithBackground : UserControl {
   public LabelWithBackground() {
      InitializeComponent();
      _label.SizeChanged += LabelSizeChanged;
   }

   void LabelSizeChanged(object sender, SizeChangedEventArgs e) {
      _labelBackground.Width = _label.ActualWidth + 
                       _label.Padding.Left + _label.Padding.Right;
   }
}
Of course you can use this UserControl in either a page (Silverlight) or in a window (WPF). In both cases you will get a label with background.
Check out my blog on Agile Leadership

No comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!