Search code examples
c#.netwpfsilverlightz-index

How to set Canvas.ZIndex to paint a black panel between the controls?


With the following code I can demonstrate how a black panel with a opacity of 50% is on top of every rectangle:

 <Grid>
    <Rectangle Fill="Black" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.5" Canvas.ZIndex="1"/>
    <Rectangle Fill="Red" Width="200" Height="200" Canvas.ZIndex="0"/>
    <Grid>
        <Rectangle Fill="Blue" Width="100" Height="100" Canvas.ZIndex="0"/>
        <Rectangle Fill="Yellow" Width="50" Height="50" Canvas.ZIndex="1"/>
    </Grid>
</Grid>

It looks like this:

enter image description here

I would like to have the yellow rectangle above the black panel, but that seems to be impossible.

I can achieve something close by setting the ZIndex of the Grid containing both the Blue and Yellow rectangles to "1". But this would also raise the blue rectangle above the black, and this is a problem.

<Grid>
    <Rectangle Fill="Black" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.5" Canvas.ZIndex="1"/>
    <Rectangle Fill="Red" Width="200" Height="200" Canvas.ZIndex="0"/>
    <Grid Canvas.ZIndex="1">
        <Rectangle Fill="Blue" Width="100" Height="100" Canvas.ZIndex="0"/>
        <Rectangle Fill="Yellow" Width="50" Height="50" Canvas.ZIndex="1"/>
    </Grid>
</Grid>

enter image description here

How do I get only the yellow rectangle above the black? In my real application I have user controls instead of the rectangles. I like to make a particular control standing out by having everything else covered by the half-black shade.

Many Thanks,


Solution

  • I don't think you'll be able to achieve this with your current arrangement of controls.

    There are two levels of controls here, the "Blue" and "Yellow" controls inside the inner grid and then the "Black" and "Red" controls together with the inner grid.

    The ZIndex works on controls at the same "level" - so you can ensure that the yellow control is on top of the blue, but then at the higher level these are grouped under the inner grid so are treated as a single unit.

    The only way this would work is if all your controls were at the same level. If you included a second semi opaque rectangle in the inner grid you could get the yellow to be on top of that but that might end up making other controls too dark.