其他分享
首页 > 其他分享> > WPF Canvas子控件拖拽行为

WPF Canvas子控件拖拽行为

作者:互联网

1

public class DragMoveBehavior: Behavior<UIElement>
    {
        Canvas parent;
        bool isDown;
        Point prePosition = new Point();

        protected override void OnAttached()
        {
            base.OnAttached();

            base.AssociatedObject.MouseLeftButtonDown += MouseLeftButtonDown;
            base.AssociatedObject.MouseLeftButtonUp += MouseLeftButtonUp;
            base.AssociatedObject.MouseLeave += MouseLeave;

            parent = LogicalTreeHelper.GetParent(base.AssociatedObject) as Canvas;
            parent.MouseLeftButtonUp += MouseLeftButtonUp;
            parent.MouseMove += MouseMove;
        }

        private void MouseMove(object sender, MouseEventArgs e)
        {
            if (!isDown) return;
            Point currentPosition = GetPosition(e);

            double offsetx = currentPosition.X - prePosition.X;
            double offsety = currentPosition.Y - prePosition.Y;
            double left = Canvas.GetLeft(AssociatedObject);
            double top = Canvas.GetTop(AssociatedObject);
            Console.WriteLine($"{left}, {top}");
            double l = double.IsNaN(left) ? 0 : left + offsetx;
            double t = double.IsNaN(top) ? 0 : top + offsety;
            Canvas.SetLeft(base.AssociatedObject, l);
            Canvas.SetTop(base.AssociatedObject, t);
            prePosition = currentPosition;
        }

        private void MouseLeave(object sender, MouseEventArgs e)
        {
            isDown = false;
            AssociatedObject.ReleaseMouseCapture();
        }

        private void MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            AssociatedObject.ReleaseMouseCapture();
            isDown = false;
        }

        private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (isDown) return;
            isDown = true;
            prePosition = GetPosition(e);
            AssociatedObject.CaptureMouse();
        }

        Point GetPosition(MouseEventArgs e)
        {
            return e.GetPosition(parent);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            base.AssociatedObject.MouseLeftButtonDown -= MouseLeftButtonDown;
            base.AssociatedObject.MouseLeftButtonUp -= MouseLeftButtonUp;
            base.AssociatedObject.MouseLeave += MouseLeave;

            parent.MouseLeftButtonUp -= MouseLeftButtonUp;
            parent.MouseMove -= MouseMove;
        }
    }

2、调用方式:

引用System.Windows.Interactivity类库;

在xaml中添加

xmlns:action="http://schemas.microsoft.com/expression/2010/interactivity"

然后在想要移动的控件里添加如下代码,比如是想拖动button:

<Button>
       <action:Interaction.Behaviors>
              <local:DragMoveBehavior />
       </action:Interaction.Behaviors>
</Button>

 

标签:控件,Canvas,parent,double,AssociatedObject,MouseLeftButtonUp,base,WPF
来源: https://www.cnblogs.com/RedSky/p/12193331.html