Ok,Better with some Corrections and APPLIED ONLY TO X COORDINATE: Given following Code:
private Point MouseDownPosition;
private void OnStartDrag(object sender, MouseButtonEventArgs e)
{
if (!this.AssociatedObject.IsMouseCaptured)
{
this.AssociatedObject.AddHandler(FrameworkElement.MouseMoveEvent, new MouseEventHandler(this.OnDrag));
this.AssociatedObject.RenderTransform = new TranslateTransform();
this.MouseDownPosition = Mouse.GetPosition(null);
Mouse.Capture(this.AssociatedObject, CaptureMode.Element);
}
}
private void OnDrag(object sender, MouseEventArgs e)
{
if (this.AssociatedObject.IsMouseCaptured)
{
this.AssociatedObject.AddHandler(FrameworkElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(this.OnStopDrag));
TranslateTransform Translate = this.AssociatedObject.RenderTransform as TranslateTransform;
Point CurrentPosition = Mouse.GetPosition(null);
Translate.X = CurrentPosition.X - this.MouseDownPosition.X;
}
}
private void OnStopDrag(object sender, MouseButtonEventArgs e)
{
if (this.AssociatedObject.IsMouseCaptured)
{
this.AssociatedObject.ReleaseMouseCapture();
this.AssociatedObject.RemoveHandler(FrameworkElement.MouseMoveEvent, new MouseEventHandler(this.OnDrag));
this.AssociatedObject.RemoveHandler(FrameworkElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(this.OnStopDrag));
}
}
1.(MouseLeftButtonDown) When I click on the FIRST time on the Dragged Object,It is moving correctely.
2.(MouseMove)I drag the object in an arbitrary position ex. 100 points right on my Panel.
3.(MouseLeftButtonUp) The object is positioned correctely WHERE I LEFT IT DRAGGING.
Until now NO problems.But when I Start the Event chain for SECOND TIME:
1.(MouseLeftButtonDown)The dragged object is shifted Back of:
CurrentPointerPosition + FIRSTPosition
2. (MouseMove)Drag move is executed but the MousePointer is at CurrentPointerPosition + FIRSTPosition FROM the dragged object.
3.(MouseLeftButtonUp) executed correctely as in First Time(but it was obvious).
It seems that on MouseLeftButtonDown the MouseDownPosition and the position of the dragged object must be resetted...
Why? What I'm doing wrong? Thank You!
Ok,after digging hours,I finally found the SOLUTION. I pray everyone really experienced in WPF/Silverlight to explain me (and others who had this problem) WHY exactely my code is working,because,sincerely,I cannot find a logical reason: