Search code examples
c#wpfcanvasz-index

child of a canvas is layered under another canvas in c#


i'm making a crossroad for a school project. i have 4 lanes with a rectangle as a car that drives on them. the problem is that car 1&2 drive under the crossroad and Panel.ZIndex doesn't seem to work.

XAML looks like this:

<grid>
  <canvas>                                //this is the 1st lane
    <rectangle x:Name= "blauweAuto" />   //this is the 1st car
  </canvas>
  <canvas>          //this is the 2nd lane
    <rectangle />   //this is the 2nd car
  </canvas>
  <canvas>          //this is the 3th lane
    <rectangle />   //this is the 3th car
  </canvas>
  <canvas>          //this is the 4th lane
    <rectangle />   //this is the 4th car
  </canvas>
</grid>

in the crossroad where al 4 canvasses overlap (yellow middle). the cars of the first drawn lanes (canvas 1 & 2) drive under the road. so i assume they are layered under the other canvasses. i tried Zindex but from what i read on the net that only works for children of the same objects. any idea's?

enter image description here

FYI i use one canvas per lane to move the car easier

private void BeweegBlauweAuto(double snelheid)
{
    blauweAuto.RenderTransform = new TranslateTransform(blauweAuto.RenderTransform.Value.OffsetX + snelheid,0);
}

//DipatcherTimer triggers this event
  private void TimerEvent(object sender, EventArgs e)
  {
      BeweegBlauweAuto(10);
  }


Solution

  • Put the ZIndex in your <canvas> element instead of the <rectangle> element. All the canvas elements are children of the <grid> element so their ZIndexes will be shared.

    As per the comments below, just re-designing your XAML structure so the canvas and car elements are not coupled with each other will be a better approach as they can be moved as two separate entities without having to worry about where they lie on the ZIndex stack.