Controlling Z-Index of children in Custom controls

In WPF, the standard way to control Z-Index (programmatically) is to use Panel.SetZIndex(). However that works well only if you plan to use a list of children inside a Panel. What if you want to get the Z-Index functionality in your own custom controls ?

Override GetVisualChild()

The way to do that is to override the GetVisualChild() method of your custom control.

The GetVisualChild() requests for a Visual at a particular index. Generally you would return the child in the same order as in your internal visual collection. This gives you the effect of the Z-order, with the 0th child at the bottom-most position and the (n-1)th child at the top-most position. If you want to change this default ordering, it is possible to do that by returning a different child at the requested index.

Reversing Z-order

Say you want to reverse the child order. In that case you could write your method like so:

 1protected override Visual GetVisualChild(int index)
 2{
 3    if (index < 0 || index >= Children.Count)
 4    {
 5        throw new Exception("Invalid Child index: " + index);
 6    }
 7
 8    int zIndex = GetZIndex(index);
 9    return Children[zIndex];
10}
11
12private int GetZIndex(int index)
13{
14    return (Children.Count - 1) - index;
15}
Thus the trick with Z-ordering lies in the particular implementation of GetVisualChild().