【问题标题】:Semitransparent background and opaque foreground wpf半透明背景和不透明前景wpf
【发布时间】:2015-11-12 10:53:31
【问题描述】:

我目前有以下 xaml 代码:

<Grid
    Name="rootGrid"
    Opacity=".25"
    Background="Black"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch">
    <Border
        Background="Black"
        Margin="120">
        <Grid
            Background="White"
            Margin="8">
            <TextBlock
                Name="popupContent">
                Test
            </TextBlock>
            <Button
                Click="Button_Click">
                Test
            </Button>
        </Grid>
    </Border>
</Grid>

目前,Grid 上的 Opacity 设置也应用于其子级。

我只想将此不透明度应用于其背景颜色,以实现变暗效果,而不是前景。我该怎么做?

【问题讨论】:

    标签: c# wpf uwp


    【解决方案1】:

    使用半透明背景,或者像 SolidColorBrush 一样

    <Grid ...>
        <Grid.Background>
            <SolidColorBrush Color="Black" Opacity="0.25"/>
        </Grid.Background>
        ...
    </Grid>
    

    或者通过在颜色中指定一个 alpha 值,比如

    <Grid Background="#3F000000" ...>
    

    【讨论】:

    • 我知道Grid.Background 可能有用,但感谢 alpha 通道的建议!
    【解决方案2】:

    诀窍是不要将Opacity 添加到整个Grid 元素中:

    <Grid>
        <Grid.Background>
            <SolidColorBrush Color="Black" Opacity=".75"/>
        </Grid.Background>
        <!--(Other elements)-->
    </Grid>
    

    【讨论】:

      【解决方案3】:

      这对我有用。我有两个网格,一个 Root 网格和 RootContent 子网格。我控制 RootContent 的不透明度。 “根”中的任何控件都不会受到影响。

      <Grid x:Name="Root" KeyDown="Root_KeyDown" Tapped="Root_Tapped">
            <!--(Other elements)-->
         <Grid x:Name="RootContent">
                <!--(Other elements)-->
         </Grid>
      </Grid>
      

      【讨论】:

        【解决方案4】:

        不透明度将始终应用于儿童,因此我倾向于使用同一级别的 Canvas 来实现这种效果:

        <Grid>
            <Canvas Opacity=".25"
                Background="Black"/>
            <Grid Name="rootGrid"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Stretch">
                <Border
                    Background="Black"
                    Margin="120">
                    <Grid
                        Background="White"
                        Margin="8">
                        <TextBlock
                            Name="popupContent">
                            Test
                        </TextBlock>
                        <Button
                            Click="Button_Click">
                            Test
                        </Button>
                    </Grid>
                </Border>
            </Grid>
        </Grid>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-30
          • 2015-07-13
          • 1970-01-01
          • 2010-12-16
          相关资源
          最近更新 更多