#xaml Canvas 事件
MouseLeftButtonDown="Canvas_MouseLeftButtonDown"
MouseMove="Canvas_MouseMove"
MouseLeftButtonUp="Canvas_MouseLeftButtonUp"
#后端
private bool isDragging;
private Point lastPosition;
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
isDragging = true;
lastPosition = e.GetPosition(ZZCeng);
ZZCeng.CaptureMouse();
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
Point currentPosition = e.GetPosition(ZZCeng);
double differenceX = currentPosition.X - lastPosition.X;
double differenceY = currentPosition.Y - lastPosition.Y;
Canvas.SetLeft(ZZCeng.Children[0], Canvas.GetLeft(ZZCeng.Children[0]) + differenceX);
Canvas.SetTop(ZZCeng.Children[0], Canvas.GetTop(ZZCeng.Children[0]) + differenceY);
lastPosition = currentPosition;
}
}
private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isDragging = false;
ZZCeng.ReleaseMouseCapture();
}
ZZCeng 为 Canvas 的 Name 名称
当鼠标左键按下时,Canvas_MouseLeftButtonDown事件被触发,开始拖动操作。在Canvas_MouseMove事件中,根据鼠标移动的距离,更新Canvas中元素的位置。当鼠标左键释放时,Canvas_MouseLeftButtonUp事件被触发,结束拖动操作。