实现控件拖动的基本原理是对鼠标位置的捕获,同时根据鼠标按键的按下,释放确定控件移动的幅度和时机。
简单示例:
在网格中有一个按钮,通过鼠标事件改编按钮的利润属性,从而改变按钮在网格中的相对位置。
& lt;网格名称=癵d”比; & lt;按钮宽度=90高度=30 Name=" btn祝辞button & lt;/Grid>
为按钮控件绑定三个事件:鼠标按下,鼠标移动,鼠标释放
公共SystemMap () { InitializeComponent (); btn。MouseLeftButtonDown +=btn_MouseLeftButtonDown; btn。MouseMove +=btn_MouseMove; btn。MouseLeftButtonUp +=btn_MouseLeftButtonUp; } >之前定义变量+鼠标按下事件
点pos=new点(); 空白btn_MouseLeftButtonDown(对象发送方,MouseButtonEventArgs e) { 按钮tmp=(按钮)发送者; pos=e.GetPosition(空); tmp.CaptureMouse (); tmp。光标=Cursors.Hand; }鼠标移动事件
空白btn_MouseMove(对象发送方,MouseEventArgs e) { 如果(e.LeftButton==MouseButtonState.Pressed) { 按钮tmp=(按钮)发送者; 双dx=e.GetPosition (null)。X - pos.X + tmp.Margin.Left; 双dy=e.GetPosition (null)。Y - pos.Y + tmp.Margin.Top; tmp。利润=new厚度(dx, dy, 0, 0); pos=e.GetPosition(空); } }鼠标释放事件
空白btn_MouseLeftButtonUp(对象发送方,MouseButtonEventArgs e) { 按钮tmp=(按钮)发送者; tmp.ReleaseMouseCapture (); }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
WPF实现控件拖动的示例代码