Drag and Drop Item Position (MouseDragElementBehavior)

I am trying to implement a WPF application with drag & drop using MouseDragElementBehavior. But I just can't find a way to get the position of the fallen elements relative to my parent Canavs. Code example:

namespace DragTest { public partial class MainWindow : Window { private Canvas _child; public MainWindow() { InitializeComponent(); Canvas parent = new Canvas(); parent.Width = 400; parent.Height = 300; parent.Background = new SolidColorBrush(Colors.LightGray); _child = new Canvas(); _child.Width = 50; _child.Height = 50; _child.Background = new SolidColorBrush(Colors.Black); MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior(); dragBehavior.Attach(_child); dragBehavior.DragBegun += onDragBegun; dragBehavior.DragFinished += onDragFinished; Canvas.SetLeft(_child, 0); Canvas.SetTop(_child, 0); parent.Children.Add(_child); Content = parent; } private void onDragBegun(object sender, MouseEventArgs args) { Debug.WriteLine(Canvas.GetLeft(_child)); } private void onDragFinished(object sender, MouseEventArgs args) { Debug.WriteLine(Canvas.GetLeft(_child)); } } } 

After deleting the child canvas, the value of Canvas.GetLeft(_child) is still 0. Why so? Why does this not change?

Of course, I can get a new position using dragBehavior.X , but the position of the child canvas in the main window, and not the position relative to the parent canvas. There must be a way to get this ...

+4
source share
1 answer

I just found a workaround:

  private void onDragFinished (object sender, MouseEventArgs args) {
     Point windowCoordinates = new Point (((MouseDragElementBehavior) sender) .X, ((MouseDragElementBehavior sender) .Y); 
     Point screenCoordinates = this.PointToScreen (windowCoordinates);
     Point parentCoordinates = _parent.PointFromScreen (screenCoordinates);
     Debug.WriteLine (parentCoordinates);
 } 

So, I just convert the coordinates of the point to the screen, then from the screen coordinate to the coordinates of the parents.

However, there will be problems if the parent canvas is in some ScrollView or somthing. It seems like a simple solution with this Drag & Drop approach ...

+1
source

All Articles