如何在WPF中覆盖父控件的不透明度? [英] How do you override the opacity of a parent control in WPF?

查看:114
本文介绍了如何在WPF中覆盖父控件的不透明度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中的Grid上设置不透明度时,所有子元素似乎都继承了其Opacity.您如何让子元素不继承父元素的不透明性?

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>

推荐答案

我能够使用画笔在纯xaml中绘制主网格背景,从而实现类似目的. 这样,只有父网格将设置其不透明度,并且其子元素将不会继承它.

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>

这篇关于如何在WPF中覆盖父控件的不透明度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆