Michel Keijzers
Michel Keijzers

Reputation: 15347

How to set the background color of a label in WPF?

I have a label but setting the Background property not seem to do anything:

    <Label Content="{Binding Name, Source={StaticResource LocStrings}}"
          HorizontalAlignment="Left" Margin="4" Name="label2"  Background="Blue" 
          VerticalAlignment="Top"/>

This does not show a blue background (while the property Background is recognized.

Also when using the Label.Background 'way' I do not see a blue background.

Update:

I used the following minimalistic code:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   Title="TEST" SizeToContent="WidthAndHeight">
    <Grid>
        <Label Content="TEXT TO TEST" Foreground="Green" Background="Orange"/>
    </Grid>
</Window>

What I see is the tekst in green but without any orange background.

Upvotes: 3

Views: 13156

Answers (2)

pushpraj
pushpraj

Reputation: 13669

Since you are binding to a string value so using a TextBlock instead of Label is worth here. A content model of Label may not be required in this scenario.

here is an example

<TextBlock Text="{Binding Name, Source={StaticResource LocStrings}}"
           HorizontalAlignment="Left" Margin="4" Name="label2"  Background="Blue" 
           VerticalAlignment="Top"/>

some other benefits of displaying text in a TextBlock instead of a Label

Unlike a Label a Textblock is derived directly from FrameworkElement instead of deriving from a Control thus making it lightweight.

A Label follows content model so the appearance may get affected by the content and its type and / or any style or template defined for the same.

read here for more Differences between Label and TextBlock

Upvotes: 2

St&#237;gandr
St&#237;gandr

Reputation: 2902

<Label Content="{Binding Name, Source={StaticResource LocStrings}}"
      HorizontalAlignment="Stretch" Margin="4" Name="label2"  Background="Blue" 
      VerticalAlignment="Top"/>

Have you tried to just enter some text in the Content and checked the binding output, maybe there is something wrong with your binding. Because it works just fine here. Note that I set HorizontalAlignment="Stretch" instead of left, which will make the label use all the horizontal avaliable space. If you don't have anything bound your label will be invisible in your case above, you may use this in combination with the output to figure out what's likely wrong with your binding as stated by others, like Sriram Sakthivel and PoweredByOrange. For helping you with that, we need a bit more information :)

Hope it helps,

Cheers,

Stian

Upvotes: 4

Related Questions