2

[Situation]

I have a custom item control which I add to a stack panel and after that is freely to move around by dragging.

public partial class CustomItem: UserControl
{
    private bool IsDragging { get; set; }
    private Point clickPosition;
    public CustomItem()
    {
        InitializeComponent();
        this.DataContext = this;
        this.MouseLeftButtonDown += (s, ea) =>
        {

            clickPosition = ea.GetPosition(this.LayoutRoot);
            this.CaptureMouse();
            IsDragging = true;
        };
        this.MouseMove += (s, ea) =>
        {
            if (IsDragging)
            {                    
                this.transFormThisShit.X = ea.GetPosition(this).X - clickPosition.X;
                this.transFormThisShit.Y = ea.GetPosition(this).Y - clickPosition.Y;
            }
        };
        this.MouseLeftButtonUp += (s, ea) =>
        {
            this.ReleaseMouseCapture();
            IsDragging = false;
        };                      
    }

[Problem]

After I add 3 items, and I drag the first item over the second or third, it jumps behind it.

When I drag the second item over the first, it goes in front but when I drag it over the third it goes behind it.

How can I make it so the control dragging is always on top of the visual tree?

Theun Arbeider
  • 5,259
  • 11
  • 45
  • 68

2 Answers2

2

You can set the ZIndex value of the item being dragged to be higher than the others. The higher the number, the 'closer' the item is to the screen, therefore the lowest number will be at the bottom.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • Lovely! Just put the grid inside a canvas and set it's property to 1 (using this.SetValue) and it worked! Thank you! – Theun Arbeider May 20 '11 at 19:33
  • Sadly this doesn't work perfectly yet untill I get a answer on my other question: http://stackoverflow.com/questions/6076206/implementing-drag-and-drop-similar – Theun Arbeider May 20 '11 at 19:51
0

Use following code to set it's Canvas.ZIndex property to something greater than 0 when you start dragging your element:

Canvas.SetZIndex(element,99);

and clear it when you are done dragging:

element.ClearValue(Canvas.ZIndex);

That should do it.

decyclone
  • 30,394
  • 6
  • 63
  • 80