WPF 實現拖動工具箱效果
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;
}
WPF 實現拖動工具箱效果