#1,172 – Custom Panel, part IV (ZIndex)

By default, a Panel control will respect its children elements’ Panel.ZIndex values when doing layout.  In the custom panel below, we overlap child elements during the arrange phase.

    public class MyPanel : Panel
    {
        protected override Size MeasureOverride(Size availableSize)
        {
            Size childSize = new Size(availableSize.Width, double.PositiveInfinity);

            foreach (UIElement elem in InternalChildren)
                elem.Measure(childSize);

            return availableSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            Size childSize;

            double top = 0.0;
            for (int i = 0; i < InternalChildren.Count; i++)
            {
                childSize = new Size(finalSize.Width, InternalChildren[i].DesiredSize.Height);
                Rect r = new Rect(new Point(0.0, top), childSize);
                InternalChildren[i].Arrange(r);
                top += childSize.Height * 0.5;
            }

            return finalSize;
        }
    }

If we don’t specify ZIndex values, each child layers on top of the previous child.
1172-001
We can reverse the order by specifying explicit ZIndex values:

    <loc:MyPanel Margin="5" Background="LightGray">
        <Label Content="I'm child #1" Panel.ZIndex="3"
               Background="Thistle" />
        <Label Content="I'm child #2" Panel.ZIndex="2"
               Background="Lavender" />
        <Label Content="Third kid"  Panel.ZIndex="1"
               Background="Honeydew" />
    </loc:MyPanel>

1172-002

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

Leave a comment