Wpf – How to override the opacity of a parent control in WPF

opacitytransparencywpf

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>

Best Answer

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>
Related Topic