Wednesday, 20 July 2016

Drag Drop on canavs C# WPF



  private bool drag = false;  //Making sure drag the object
        private Point StartPoint;
        private int RectangleWidth;
        private int RectangleHeight;
        private Point LastLocation;
        private double CanvasLeft, CanvasTop;

private void Circle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                RectangleSelected = (Image)sender;
                drag = true;
                Cursor = Cursors.Hand;
                StartPoint = e.GetPosition(CanvasOuter);
                LastLocation = new Point(selectedCircle.X, selectedCircle.Y);
                Mouse.Capture((IInputElement)sender);
            }
            catch (Exception ex)
            {
                var methodName = new StackTrace(ex).GetFrame(0).GetMethod().Name;
                Errorlog.Errorlog.WriteToErrorLog(ex.Message, ex.StackTrace, "Error", methodName);
            }
        }

        private void Circle_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (drag)
                {
                    var newX = (StartPoint.X + (e.GetPosition(this).X - StartPoint.X));
                    var newY = (StartPoint.Y + (e.GetPosition(this).Y - StartPoint.Y));
                    Point offset = new Point((StartPoint.X - LastLocation.X), (StartPoint.Y - LastLocation.Y));
                    CanvasTop = newY - offset.Y;
                    CanvasLeft = newX - offset.X;

                    // check if the drag will pull the rectangle outside of it's host canvas before performing
                    // TODO: protect against lower limits too...
                    if ((CanvasTop + RectangleSelected.Height > CanvasOuter.Height) || (CanvasLeft + RectangleSelected.Width > CanvasOuter.Width) || CanvasTop < 0 || CanvasLeft < 0)
                    {
                        return;
                    }
                    RectangleSelected.SetValue(Canvas.TopProperty, CanvasTop);
                    RectangleSelected.SetValue(Canvas.LeftProperty, CanvasLeft);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Circle_MouseUp(object sender, MouseButtonEventArgs e)
        {
            drag = false;
            Cursor = Cursors.Arrow;
            Mouse.Capture(null);
        }

No comments:

Post a Comment