#1,045 – Control Layering of Elements in a Grid Using ZIndex

If you have more than one user interface element in a particular grid cell, the elements are layered on top of each other.  Elements added earlier in XAML appear below (lower layer) than elements added later.

You can change the layering of the elements by changing the order in which they are added to the Grid.  You can also control the layering by giving each element a value for Panel.ZIndex.  Elements with higher values for ZIndex will appear to be on top of elements with lower values, regardless of the order in which they were added to the Grid.

In the example below, the Label appears on top of the Button because it has a higher value for ZIndex.

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Label Content="Oops I'm in the same cell with a button !"
               Panel.ZIndex="2"/>
        <Button Content="Push Me" Width="100"
                Panel.ZIndex="1"/>
    </Grid>

1045-001

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,045 – Control Layering of Elements in a Grid Using ZIndex

  1. Fred says:

    Hey Sean,

    where is the Panel declared? If I try to use a dependency property of the UIElements, I cannot see a Panel in there.

    All the best!
    Fred

    • Sean says:

      Panel is a class in System.Windows.Controls that Grid inherits from. Grid uses the ZIndex property when organizing children (other layout panels also use it). You can set Panel.ZIndex on any element, of course. But when you set it on child elements in a Grid, the Grid will read the property value and use it for layout.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: