#806 – Setting ZIndex Values of Child Elements in a Canvas from Code

You use the Canvas.ZIndex attached property on a child element in a Canvas to indicate the relative positioning of elements, when they happen to overlap.  Elements that have higher ZIndex values will appear on top of elements having lower values.

        <Button Content="1 - Lft10,Top10" Canvas.Left="10" Canvas.Top="10"
                Canvas.ZIndex="4"/>
        <Button Content="2 - Rt10,Top10" Canvas.Right="10" Canvas.Top="15"
                Canvas.ZIndex="3"/>
        <Button Content="3 - Lft10,Bott10..." Canvas.Left="15" Canvas.Bottom="15"
                Canvas.ZIndex="2"/>
        <Button Content="4 - Rt10,Bott10" Canvas.Right="10" Canvas.Bottom="8"
                Canvas.ZIndex="1"
                Click="Button_Click"/>

806-001
As with other attached properties, you can set the value from code by using a static method of the form SetPropName.  In the case of ZIndex, you use the static Canvas.SetZIndex method, passing in a reference to child control.

private void Button_Click(object sender, RoutedEventArgs e)
{
    Canvas.SetZIndex(sender as UIElement, 5);
}