好的,进行一些更正会更好,并且仅适用于 X 坐标:给定以下代码:
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)当我第一次点击拖动对象时,它正在正确移动。
2.(鼠标移动)我将对象拖动到任意位置。我的面板上有 100 分。
3.(MouseLeftButtonUp)对象被正确定位在我拖拽的地方。
到目前为止没有问题。但是当我第二次启动事件链时:
1.(MouseLeftButtonDown)被拖动的对象移到后面:
CurrentPointerPosition + FIRSTPosition
2. (MouseMove)执行拖动移动,但鼠标指针位于 CurrentPointerPosition + FIRSTPosition FROM 拖动对象。
3.(MouseLeftButtonUp) 与第一次一样正确执行(但很明显)。
似乎在 MouseLeftButtonDown 上,必须重置 MouseDownPosition 和拖动对象的位置......
为什么?我做错了什么?谢谢你!