How to drag a UserControl inside a Canvas

后端 未结 7 1216
Happy的楠姐
Happy的楠姐 2020-11-28 07:28

I have a Canvas in which user can add UserControl subclasses containing a form. User should be able to drag these UserControl around the Canvas.

What\'s the best pr

7条回答
  •  孤城傲影
    2020-11-28 07:41

    If someone wants to quickly see this effect, here is a minimal solution using only MouseMove event.

    The Layout

    
            
        
    

    Code behind

     private void OnMouseMove(object sender, MouseEventArgs e)
            {
                if (e.Source is Shape shape)
                {
                    if (e.LeftButton == MouseButtonState.Pressed)
                    {
                        Point p = e.GetPosition(canvas);
                        Canvas.SetLeft(shape, p.X - shape.ActualWidth / 2);
                        Canvas.SetTop(shape, p.Y - shape.ActualHeight / 2);
                        shape.CaptureMouse();
                    }
                    else
                    {
                        shape.ReleaseMouseCapture();
                    }
                }
            }
    

提交回复
热议问题