How to drag a UserControl inside a Canvas

后端 未结 7 1218
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 08:02

    I had some trouble with the given solutions and ended up with this:

        public partial class UserControlDraggable : UserControl
    {
        public UserControlDraggable()
        {
            InitializeComponent();
    
            MouseLeftButtonDown += new MouseButtonEventHandler(Control_MouseLeftButtonDown);
            MouseLeftButtonUp += new MouseButtonEventHandler(Control_MouseLeftButtonUp);
            MouseMove += new MouseEventHandler(Control_MouseMove);
        }
    
        private void Control_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _isDragging = true;
            _mouseLocationWithinMe = e.GetPosition(this);
    
            CaptureMouse();
        }
    
        private void Control_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isDragging = false;
            this.ReleaseMouseCapture();
        }
    
        private void Control_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDragging)
            {
                var mouseWithinParent = e.GetPosition(Parent as UIElement);
    
                Canvas.SetLeft(this, mouseWithinParent.X - _mouseLocationWithinMe.X);
                Canvas.SetTop(this, mouseWithinParent.Y - _mouseLocationWithinMe.Y);
            }
        }
    
        protected bool _isDragging;
        Point _mouseLocationWithinMe;
    }
    

    It is basically Corey's example but leverages hints from Hawlett. It works ONLY when the parent container is a Canvas. Also, it deserves to be dolled up with some limits to keep the user from dragging the control to places it really should not be.

    0 讨论(0)
提交回复
热议问题