前台代码,在窗体里加入了一个Button控件
<Window x:Class="DragMove.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DragMove"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid Name="grid">
<Button Name="button"
Content="Drag Move This Button"
Height="30"
Width="160"/>
<Grid Width="50" Height="150">
<Canvas x:Name="canvas"
Height="50"
Width="50"
Background="Red"
MouseDown="c_MouseDown"
MouseMove="c_MouseMove"
MouseUp="c_MouseUp">
<TextBlock Text="123456"/>
</Canvas>
</Grid>
</Grid>
</Window>
后台代码
namespace DragMove
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Button控件在捕获了MouseLeftButtonDown事件后,会将该事件的“Handled”设置为true;
// 这个属性是用在事件路由中的,当某个控件得到一个RoutedEvent,就会检测Handled是否为true,为true则忽略该事件;
// 由于Button控件本身的Click事件,相当于将MouseLeftButtonDown事件抑制(Supress)掉了,转换成了Click事件;
// 所以,如果一定要使用这个事件的话,需要在初始化的函数里利用UIElement的AddHandler方法,显式的增加这个事件;
button.AddHandler(Button.MouseLeftButtonDownEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonDown), true);
button.AddHandler(Button.MouseLeftButtonUpEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonUp), true);
button.AddHandler(Button.MouseMoveEvent, new MouseEventHandler(this.Button_MouseMove), true);
}
#region button 移动代码
private void Button_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Button tmp = (Button)sender;
double dx = e.GetPosition(null).X - pos.X + tmp.Margin.Left;
double dy = e.GetPosition(null).Y - pos.Y + tmp.Margin.Top;
tmp.Margin = new Thickness(dx, dy, 0, 0);
pos = e.GetPosition(tmp);
}
}
Point pos = new Point();
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Button tmp = (Button)sender;
pos = e.GetPosition(this.button);
this.button.CaptureMouse();
this.button.Cursor = Cursors.Hand;
}
private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Button tmp = (Button)sender;
tmp.ReleaseMouseCapture();
}
#endregion
#region canvas移动代码
Point mousePoint = new Point();
private void c_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
mousePoint = e.GetPosition(this.canvas);
canvas.CaptureMouse();
canvas.Cursor = Cursors.Hand;
}
}
private void c_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Canvas tmp = (Canvas)sender;
double dx = e.GetPosition(this.canvas).X - mousePoint.X + tmp.Margin.Left;
double dy = e.GetPosition(this.canvas).Y - mousePoint.Y + tmp.Margin.Top;
tmp.Margin = new Thickness(0, dy, 0, 0);
mousePoint = e.GetPosition(tmp);
}
}
private void c_MouseUp(object sender, MouseButtonEventArgs e)
{
this.canvas.ReleaseMouseCapture();
}
#endregion
}
}