Wpf 鼠标拖动元素实例
1.Wpf中鼠标捕获和释放
//以矩形为例 //创建鼠标捕获 Mouse.Capture(rectOne); //释放鼠标捕获 rectOne.ReleaseMouseCapture();
2.Wpf中在定位布局Canvas下获取或设置元素的位置
在指定元素的鼠标事件中例如,MouseLeftButtonDown,MouseLeftButtonUp,MouseMove获取当前鼠标相对于Canvas 的位置,以及位置操作
//获取鼠标位置 e.GetPosition(canvasOne).X e.GetPosition(canvasOne).Y //获取元素位置 Canvas.GetLeft(rectOne) Canvas.GetTop(rectOne) //设置指定元素位置等 Canvas.SetLeft(rectOne, cLeft) Canvas.SetTop(rectOne, cTop)
3.拖动实例代码:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); //注册移动事件 rectOne.MouseLeftButtonDown += rectOne_MouseLeftButtonDown; rectOne.MouseLeftButtonUp += rectOne_MouseLeftButtonUp; rectOne.MouseMove += rectOne_MouseMove; } bool enableMove = false; double spanLeft = 0; double spanTop = 0; //鼠标移动 private void rectOne_MouseMove(object sender, MouseEventArgs e) { if (enableMove) { var cLeft = e.GetPosition(canvasOne).X - spanLeft; var cTop = e.GetPosition(canvasOne).Y - spanTop; //设置矩形的位置 Canvas.SetLeft(rectOne, cLeft); Canvas.SetTop(rectOne, cTop); } } //鼠标松开 private void rectOne_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { //释放鼠标捕获 rectOne.ReleaseMouseCapture(); enableMove = false; spanLeft = spanTop = 0; } //鼠标按下 private void rectOne_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { //创建鼠标捕获 Mouse.Capture(rectOne); enableMove = true; spanLeft = e.GetPosition(canvasOne).X - Canvas.GetLeft(rectOne); spanTop = e.GetPosition(canvasOne).Y - Canvas.GetTop(rectOne); } }