#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: