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:
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= Children.Count)
{
throw new Exception("Invalid Child index: " + index);
}
int zIndex = GetZIndex(index);
return Children[zIndex];
}
private int GetZIndex(int index)
{
return (Children.Count - 1) - index;
}
Thus the trick with Z-ordering lies in the particular implementation of GetVisualChild().