JKennedy
JKennedy

Reputation: 18827

How to make a background transparent without affecting child elements in WPF

Say if I have:

<Grid Background="LightGray" Margin="2,4,2,4" Opacity="0.5">
<Image Source="{Binding FullName}" Width="300" Height="170" />
</Grid>

This will also make the Image have an Opacity of 0.5. Is it possible to have the background transparent while the Image remains with an Opacity of 1

Upvotes: 1

Views: 1290

Answers (3)

clcto
clcto

Reputation: 9648

Background can take a color in hex format as well:

a is alpha
r is red
g is green
b is blue

Possible formats (from here)

<object property="predefinedBrushName"/>
- or -
<object property="#rgb"/>
- or -
<object property="#argb"/>
- or -
<object property="#rrggbb"/>
- or -
<object property="#aarrggbb"/>
- or -
<object property="sc#scA,scR,scG,scB"/>
- or -
<object property="ContextColor profileUri alphaValue,colorValue"/>

So we can use Background="#80D3D3D3" ((LightGray is defined as #FFD3D3D3 so I changed the opacity to 50%)

<Grid Background="#80D3D3D3" Margin="2,4,2,4">
    <Image Source="{Binding FullName}" Width="300" Height="170" />
</Grid>

Upvotes: 1

Daniel May
Daniel May

Reputation: 8246

You could specify the opacity in the brush used for the Grid's Background property rather than applying the opacity to the entire Grid element..

WPF's LightGray is #FFD3D3D3 - so you could use #80D3D3D3.

Upvotes: 1

Gusdor
Gusdor

Reputation: 14322

You need to specify your own Brush object with an alpha channel (opacity) component that is not 1.

<Grid>
    <Grid.Background>
       <SolidColorBrush Color="#FF295564" Opacity="0.3"/>
    </Grid.Background>
</Grid>

It is worth noting that the first byte of the color's hex value is the alpha transparency but the Opacity property lets you use a double, not an unsigned byte. It is slightly easier to read.

Upvotes: 7

Related Questions