WPF布局(2)-控件拖动

从Window继承的控件窗体,实现窗体拖动时可以简单的调用DragMove方法。但是对于自定义控件可以采取响应MouseButtonDown,MouseMove,MouseButtonUp的方法来实现控件的拖动。首先定义两个位置变量:

   Point pOld = new Point();
   Point pNew = new Point();

1、MouseButtonDown

在此函数中实现坐标的获取,并且捕获鼠标

 pOld = Mouse.GetPosition(relativeWindow);//坐标窗体
TextBlock tb = (TextBlock)sender;
 tb.CaptureMouse();//捕获鼠标,如果不调用此函数,则鼠标移出该对象时,不会响应MouseButtonUp事件。

2、MouseMove

在此函数中实现坐标的计算,如:

if (e.LeftButton != MouseButtonState.Pressed)
                return;
 pNew = Mouse.GetPosition(relativeWindow);
 this.Left += pNew.X - pOld.X;
this.Top += pNew.Y - pOld.Y;
pOld = pNew;

3、MouseButtonUp

在此函数中,释放对鼠标的捕捉。

TextBlock tb = (TextBlock)sender;
            tb.CaptureMouse();
            if (tb.IsMouseCaptured == true)
            {   
                tb.ReleaseMouseCapture();
            }

 

你可能感兴趣的:(WPF)