如何将DragDrop Adorner放置在光标的尖端?

时间:2019-03-29 13:16:54

标签: wpf drag-and-drop adorner

我正在尝试使其看起来像用户在拖动原始控件的克隆

我有一个装饰器,在拖动时会在光标底部显示控件的克隆。如何将装饰物定位在光标的位置。理想情况是从原始控件的确切位置开始。

我的Adorner代码如下:

    class MyAdorner : Adorner
    {
        private Control _control;
        private double _x_offset = 0;
        private double _y_offset = 0;

        public MyAdorner(Control control) : base(control)
        {
            IsHitTestVisible = false;
            _control = control;
            AddVisualChild(_control);
        }

        public void UpdatePosition(double x, double y)
        {
            _x_offset = x;
            _y_offset = y;
            AdornerLayer layer = Parent as AdornerLayer;
            if (layer != null)
            {
                layer.Update(AdornedElement);
            }
        }

        protected override Size MeasureOverride(Size constraint)
        {
            _control.Measure(constraint);
            return _control.DesiredSize;

        }
        protected override Size ArrangeOverride(Size finalSize)
        {
            _control.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override int VisualChildrenCount
        {
            get { return 1; }
        }

        protected override Visual GetVisualChild(int index)
        {
            return _control;
        }

        public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
        {
            var animationDuration = TimeSpan.FromSeconds(0);
            var translate_transform = new TranslateTransform();

            translate_transform.BeginAnimation(TranslateTransform.XProperty,
                new DoubleAnimation(_x_offset, new Duration(animationDuration)));

            translate_transform.BeginAnimation(TranslateTransform.YProperty,
                new DoubleAnimation(_y_offset, new Duration(animationDuration)));

            return translate_transform;

        }
    }

我这样创建装饰器:

protected override void OnPreviewMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        AdornerLayer ad_layer = AdornerLayer.GetAdornerLayer(this);
        _adorner = new MyAdorner(new MyControl());
        ad_layer.Add(_adorner);

        Visibility = Visibility.Hidden;
        _window.DragOver += _window_DragOver;
        DragDrop.DoDragDrop(this, "data", DragDropEffects.All);
        Visibility = Visibility.Visible;
        ad_layer.Remove(_adorner);
    }
}

private void _window_DragOver(object sender, DragEventArgs e)
{
    Point pos = e.GetPosition(sender as Window);
    _adorner.UpdatePosition(pos.X, pos.Y);
}

注意:我正在将控件从一个面板拖到另一个面板。这就是为什么我连接窗口事件以捕获鼠标在窗口中任何位置的原因。

0 个答案:

没有答案