vrwim
vrwim

Reputation: 14300

Semitransparent background and opaque foreground wpf

I currently have the following xaml code:

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

Currently, the Opacity setting on the Grid is also applied on its children.

I only want this opacity to be applied on its background color, to achieve a darkening effect, not on the foreground. How can I do this?

Upvotes: 1

Views: 6844

Answers (4)

Tim
Tim

Reputation: 1

This worked for me. I have two Grids a Root grid and RootContent sub-grid. I control the Opacity of the RootContent. Any controls in the "Root" will not be effected.

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

Upvotes: 0

vrwim
vrwim

Reputation: 14300

The trick is to not add the Opacity to the entire Grid element:

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

Upvotes: 0

Glen Thomas
Glen Thomas

Reputation: 10744

The opacity will always apply to children, so I tend to use a Canvas at the same level to achieve this affect:

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

Upvotes: -1

Clemens
Clemens

Reputation: 128061

Use a semi-transparent background, either as a SolidColorBrush like

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

or by specifying an alpha value in the color, like

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

Upvotes: 10

Related Questions