Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

transparency - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...