How can I set multiple backgrounds for a grid in WPF?

267 views Asked by At

I have a grid, which has 2 rows and 3 columns. I need 2 background images for my grid - one will be on the top of the other. (ZIndex of one background should be bigger than other background has). How can I achieve this?

I will need to swap these 2 backgrounds frequently, which means the top background will become lower background and lower background will become top background. Apart from that, images of these two backgrounds are gonna change a lot too.

This example has grid, which contains text switcher at the bottom. As a background, it has a picture of room. When I click 'next' button in the text switcher, I want the top background picture to gradually disappear (doubleAnimation updates opacity) and show lower background under it. Maybe I can achieve gradual switching of backgrounds in a better way, but I honestly dont know how to do it. enter image description here

2

There are 2 answers

3
Mark Feldman On

You can draw them as two images on a Canvas inside a VisualBrush and use that as your background:

<Grid>
    <Grid.Background>
        <VisualBrush>
            <VisualBrush.Visual>
                <Canvas Width="256" Height="256">
                    <Image Source="image1.png" Panel.ZIndex="1" /> <!-- This will appear over top of the other one -->
                    <Image Source="image2.png" Panel.ZIndex="0" /> 
                </Canvas>
            </VisualBrush.Visual>
        </VisualBrush>
    </Grid.Background>
</Grid>

Source and Panel.ZIndex can then be set either directly in code-behind or via data binding.

This is a bit of an unsual way of going about this though, there's almost certainly a better way of doing whatever it is you're actually trying to do.

0
BWayne On

In this case I would use databinding to bind to a property in the view model that stores the background image. When the condition changes and the view model property is changed the UI will reflect those changes.