Over a million developers have joined DZone.

Adding an Image Background to a TextBlock in Windows Phone

· Mobile Zone

Here is the scenario: On my MainPage I have three TextBlocks:

1


In TextBlock 2 I want to have an Image Background. The problem is that a TextBlock does not have a Background property. What I have to do is to add the TextBlock to a layout control and set its Background property. There are different ways to do this:

1. Add the TextBlock to a Grid and set the Background property of the Grid:

<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
           Text="Test in TextBlock1"/>
<Grid
    Grid.Row="1">
    <Grid.Background>
        <ImageBrush ImageSource="/TextBlockBackground;component/Images/MyImage.jpg"
                    Opacity="0.2"/>
    </Grid.Background>
    <TextBlock Text="Test in TextBlock2" />
</Grid>
<TextBlock Grid.Row="2"
           Text="Test in TextBlock3" />

2. In this case you might to apply additional Margins:

<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
           Text="Test in TextBlock1"/>
<Grid Grid.Row="1">
    <Image Source="/TextBlockBackground;component/Images/MyImage.jpg" />
    <TextBlock Text="Test in TextBlock2"
               Height="50"
               Width="200"/>
</Grid>
<TextBlock Grid.Row="2"
           Text="Test in TextBlock3" />

3. The (in my opinion) easiest approach is to put a Border around the TextBlock:

<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
           Text="Test in TextBlock1"/>
<Border Grid.Row="1">
    <Border.Background>
        <ImageBrush ImageSource="/TextBlockBackground;component/Images/MyImage.jpg"
                    Opacity="0.2"/>
    </Border.Background>
    <TextBlock Grid.Row="1"
           Text="Test in TextBlock2"/>
</Border>
<TextBlock Grid.Row="2"
           Text="Test in TextBlock3" />


Which approach you take is a matter of personal taste. The result is the same:

2

 

To be continued…


Source: http://andreahaubner.blog.com/2011/11/14/image-background-in-a-textblock/

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}