themaestro
themaestro

Reputation: 14256

How to Control Z Order of Grids

I have the following code:

        TextBlock tmp = new TextBlock
        {
            Text = displayText,
            Foreground = new SolidColorBrush(Colors.Red),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
            FontSize = 30
        };
        Grid grd = new Grid();
        grd.Children.Add(tmp);
        // grd.Background = new SolidColorBrush(Colors.LightGray);
        Viewbox vb = new Viewbox();
        vb.Child = grd;
        vb.Width = width;
        vb.Height = height;
        DrawingCvs.Children.Add(vb);
        Canvas.SetLeft(vb, xpos);
        Canvas.SetTop(vb, ypos);
        Canvas.SetZIndex(grd, 1000);

        // we need a second grid for cosmetic reasons. Due to
        // how the viewbox works, when we resize we lose the full
        // width of the grid which has a textblock in it
        Grid cosmeticGrd = new Grid
                          {
                              Width = width,
                              Height = height,
                              Background = new SolidColorBrush(Colors.LightGray)
                          };
        DrawingCvs.Children.Add(cosmeticGrd);
        Canvas.SetLeft(cosmeticGrd, xpos);
        Canvas.SetTop(cosmeticGrd, ypos);
        Canvas.SetZIndex(grd, 0);

What I want is for the Grid added first in the code to be above the grid added second. What is wrong with my Z-Index property setting here? Or is it something else?

InB4 Change the order you add them in the code--yes I realize this, but as a point of understanding I want to understand the ZIndex property.

Upvotes: 0

Views: 3448

Answers (1)

Rick Sladkey
Rick Sladkey

Reputation: 34240

Your first SetZindex call:

Canvas.SetZIndex(grd, 1000);

incorrectly applies the setting to the Grid instead of the Viewbox. It should be:

Canvas.SetZIndex(vb, 1000);

because the Viewbox is the child of the Canvas.

Likewise, your second SetZIndex call:

Canvas.SetZIndex(grd, 0);

is applied to the wrong Grid. It should be:

Canvas.SetZIndex(cosmeticGrd, 0);

In summary, the Canvas.ZIndex attached property affects the ordering of Canvas children.

Upvotes: 1

Related Questions