1

I have a form where the user can select various form elements and drag them around. Since the user can customize the layout of the form I am using a canvas and all of the elements are children of it.

When two elements are in the same region whichever one was added last as a child of the canvas will be drawn on top. I want to be able to make whatever the active element, the one being dragged, to be set to be the topmost element.

I played around with the SetZOrder method, setting it to 0, but it does nothing. Upon inspection all of my elements calling GetZOrder I get a 0 for each of them, which is why setting it to 0 doesn't make a difference.

The only solution that I have found, and it does work, is to remove and add the element to the canvas.

        _mainCanvas.Children.Remove(_selectedElement);
        _mainCanvas.Children.Add(_selectedElement);

While this works, I feel there must be a more prefered and proper way of doing this.

WPFNewbie
  • 2,464
  • 6
  • 34
  • 45
  • have you looked at this article by Josh Smith: http://www.codeproject.com/KB/WPF/DraggingElementsInCanvas.aspx – Muad'Dib Dec 06 '11 at 19:51

1 Answers1

1

The ZIndex does determine which is top most. The highest ZIndex wins. Try setting ZIndex of the one you want to be topmost to a number higher than the ZIndex of the others.

Chris E
  • 973
  • 13
  • 26
  • 2
    It's [`ZIndex`](http://msdn.microsoft.com/en-us/library/system.windows.controls.panel.zindex.aspx).. – H.B. Dec 06 '11 at 19:56
  • @H.B. woops! That's what I get for doing it from memory. Fixed. – Chris E Dec 06 '11 at 19:59
  • My issue is that ZIndex defaults to 0. It does not protect against more than one control having the same ZIndex. I could default all controls to a ZIndex of 1, then when you select a control set the ZIndex to 0, but then I also have to set it back to 1 when it is unselected. I was hoping I could just set the ZIndex to 0 and it would automatically shift all of the other ZIndex values, then you wouldn't have to care about tracking the previously selected elements and setting the ZIndex back to something higher. At that point just removing and adding the control seems simplier. – WPFNewbie Dec 06 '11 at 20:09