1.效果
点击左边的矩形拖动到右边canvas面板,右边面板添加矩形
2.布局
左边是个StockPanel,上面有个矩形,右边是个Canvas面板。
矩形是源,Canvas面板是目的,AllowDrop属性都要设成true,矩形框要有填充色,Canvas要有background,否则无法响应鼠标拖拽事件。
3.矩形框点击事件
private void rectangle1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Rectangle rect = sender as Rectangle;
//创建新矩形
Rectangle temp = new Rectangle();
temp.Width = rect.Width;
temp.Height = rect.Height;
temp.Fill = rect.Fill;
temp.Stroke = rect.Stroke;
//添加移动事件
temp.MouseLeftButtonDown += new MouseButtonEventHandler(module_MouseLeftButtonDown);
temp.MouseMove += new MouseEventHandler(module_MouseMove);
temp.MouseLeftButtonUp += new MouseButtonEventHandler(module_MouseLeftButtonUp);
DragDrop.DoDragDrop(temp, temp, DragDropEffects.Copy);
}
4.Canvas响应事件
private void canvas1_Drop(object sender, DragEventArgs e)
{
Rectangle r = (Rectangle)e.Data.GetData(typeof(Rectangle));
Point p = e.GetPosition(canvas1);
r.SetValue(Canvas.TopProperty, p.Y-r.Height/2);
r.SetValue(Canvas.LeftProperty, p.X-r.Width/2);
canvas1.Children.Add(r);
}
5.Canvas内的矩形拖动
void module_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Rectangle rect = sender as Rectangle;
mouseposition = e.GetPosition(canvas1);
mousedown = true;
rect.CaptureMouse();
}
void module_MouseMove(object sender, MouseEventArgs e)
{
Rectangle rect = sender as Rectangle;
if (mousedown) {
double deltav = e.GetPosition(canvas1).Y - mouseposition.Y;
double deltah = e.GetPosition(canvas1).X - mouseposition.X;
double newtop = deltav + (double)rect.GetValue(Canvas.TopProperty);
double newleft = deltah + (double)rect.GetValue(Canvas.LeftProperty);
rect.SetValue(Canvas.TopProperty, newtop);
rect.SetValue(Canvas.LeftProperty, newleft);
mouseposition = e.GetPosition(canvas1);
}
}
void module_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Rectangle rect = sender as Rectangle;
mousedown = false;
rect.ReleaseMouseCapture();
mouseposition.X = mouseposition.Y = 0;
}