一步一步学Silverlight :实现简单的拖放功能
开始拖放操作
开始拖放操作,实现MouseLeftButtonDown事件处理程序,用两个全局变量来记录当前鼠标的位置和鼠标是否保持移动。
bool trackingMouseMove = false; Point mousePosition; void OnMouseDown(object sender, MouseButtonEventArgs e) { FrameworkElement element = sender as FrameworkElement; mousePosition = e.GetPosition(null); trackingMouseMove = true; if (null != element) { element.CaptureMouse(); element.Cursor = Cursors.Hand; } }
移动对象
移动对象,实现MouseMove事件处理程序,计算元素的位置并更新,同时更新鼠标的位置。
void OnMouseMove(object sender, MouseEventArgs e) { FrameworkElement element = sender as FrameworkElement; if (trackingMouseMove) { double deltaV = e.GetPosition(null).Y - mousePosition.Y; double deltaH = e.GetPosition(null).X - mousePosition.X; double newTop = deltaV + (double)element.GetValue(Canvas.TopProperty); double newLeft = deltaH + (double)element.GetValue(Canvas.LeftProperty); element.SetValue(Canvas.TopProperty, newTop); element.SetValue(Canvas.LeftProperty, newLeft); mousePosition = e.GetPosition(null); } }