#1,172 – Custom Panel, part IV (ZIndex)
October 3, 2014 Leave a comment
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.
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>