我试图用行为拖动画布,我让它适合水平移动,但我不能让它与垂直移动一起工作。当我尝试垂直拖动它时,当我向上移动鼠标时它会跳起来,当我向下移动鼠标时它也会跳起来。它以很大的增量向上移动。水平运动虽然很好,但代码也是一样的。
以下是我的行为代码。
public class MouseDragPopupBehavior : Behavior<Grid>
{
private bool _mouseDown;
private Point _oldMousePosition;
/// <summary>
/// Called after the behavior is attached to an AssociatedObject.
/// </summary>
/// <remarks>
/// Override this to hook up functionality to the AssociatedObject.
/// </remarks>
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += (sender, e) =>
{
_mouseDown = true;
_oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
AssociatedObject.CaptureMouse();
};
AssociatedObject.MouseMove += (sender, e) =>
{
if (!_mouseDown) return;
Point newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
Vector offset = newMousePosition - _oldMousePosition;
_oldMousePosition = newMousePosition;
double horizontalMovement = Canvas.GetLeft(AssociatedObject) + offset.X;
double verticalMovement = Canvas.GetTop(AssociatedObject) + offset.Y;
// Works
//double marginShift = AssociatedObject.Margin.Top + offset.Y;
//AssociatedObject.Margin = new Thickness(0, marginShift, 0, 0);
Canvas.SetLeft(AssociatedObject, horizontalMovement);
// Does not work
Canvas.SetTop(AssociatedObject, verticalMovement);
};
AssociatedObject.MouseLeftButtonUp += (sender, e) =>
{
_mouseDown = false;
AssociatedObject.ReleaseMouseCapture();
};
}
}
我的代码适用于水平(从左到右)移动,但不适用于垂直移动。我确实通过设置边距来获得垂直移动,如注释部分所示,但我真的想让它以其他方式工作。
感谢您的帮助。