Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you override the opacity of a parent control in WPF?

When you set the opacity on a Grid in WPF, all the child elements appear to inherit its Opacity. How can you have a child element not inherit the parent's opacity?

For example, the following parent grid has one child grid in the middle with a background set to red, but the background appears pinkish because of the parent's opacity. I'd like the child grid to have a solid color, non-transparent background:

<Grid x:Name="LayoutRoot">    <Grid Background="Black" Opacity="0.5">     <Grid.RowDefinitions>       <RowDefinition Height="0.333*"/>       <RowDefinition Height="0.333*"/>       <RowDefinition Height="0.333*"/>     </Grid.RowDefinitions>     <Grid.ColumnDefinitions>       <ColumnDefinition Width="0.333*"/>       <ColumnDefinition Width="0.333*"/>       <ColumnDefinition Width="0.333*"/>     </Grid.ColumnDefinitions>      <-- how do you make this child grid's background solid red         and not inherit the Opacity/Transparency of the parent grid? -->     <Grid Grid.Column="1" Grid.Row="1" Background="Red"/>   </Grid>  </Grid> 
like image 350
Metro Smurf Avatar asked Apr 16 '10 04:04

Metro Smurf


People also ask

How do you inherit opacity?

Opacity is not inherited, but because the parent has opacity that applies to everything within it. You cannot make a child element less transparent than the parent, without some trickery. Values are a number from 0 to 1 representing the opacity of the channel (the “alpha” channel).

What is opacity WPF?

All WPF controls are inherited from UIElement. The Opacity property of UIElement is used to set transparency of a control. The value of Opacity falls between 0.0 and 1.0 where 0.0 is fully transparent and 1.0 is fully opaque.

Where is parent control in WPF?

Use MessageBox to display a dialog box that appears in the caller's central, obviously, to do this, MessageBox must get the parent control, so as to calculate the center position.


1 Answers

I was able to achieve something like this in pure xaml using a Brush to paint the main grids background. This way only parent grid will have its opacity set and its child elements won't inherit it.

<Grid x:Name="LayoutRoot">              <Grid>         <Grid.Background>             <SolidColorBrush Color="Black" Opacity="0.5"/>         </Grid.Background>         <Grid.RowDefinitions>           <RowDefinition Height="0.333*"/>           <RowDefinition Height="0.333*"/>           <RowDefinition Height="0.333*"/>         </Grid.RowDefinitions>         <Grid.ColumnDefinitions>           <ColumnDefinition Width="0.333*"/>           <ColumnDefinition Width="0.333*"/>           <ColumnDefinition Width="0.333*"/>         </Grid.ColumnDefinitions>          <Grid Grid.Column="1" Grid.Row="1" Background="Red" />       </Grid>    </Grid> 
like image 188
chiefanov Avatar answered Sep 26 '22 22:09

chiefanov