在拖动和移动中移动画布上的控件下降

时间:2018-05-16 06:35:49

标签: c# wpf wpf-controls

我在画布上放置了文本块。我使用以下代码更改了鼠标拖动的位置:

   protected bool isDragging;
   private Point clickPosition;

   private void txt_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
            isDragging = true;
            var draggableControl = sender as TextBlock;
            clickPosition = e.GetPosition(this);
            draggableControl.CaptureMouse();
    }

    private void txt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        isDragging = false;
        var draggable = sender as TextBlock;
        draggable.ReleaseMouseCapture();
    }

    private void txt_MouseMove(object sender, MouseEventArgs e)
    {
        var draggableControl = sender as TextBlock;

        if (isDragging && draggableControl != null)
        {
            Point currentPosition = e.GetPosition(this.Parent as UIElement);

            var transform = draggableControl.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                draggableControl.RenderTransform = transform;
            }

            transform.X = currentPosition.X - clickPosition.X;
            transform.Y = currentPosition.Y - clickPosition.Y;
        }
    }

我想要的是获取文本块的新位置,保存它,下次加载应用程序时,控件应该采用新的位置。我知道我的代码不会改变Left&文本块的顶级属性,而是转换它。因此,Left和Top Property不会被改变。 我试图将Left和Top Property设置为

            draggableControl.SetValue(Canvas.LeftProperty, transform.X);
            draggableControl.SetValue(Canvas.TopProperty, transform.Y);

但它也没有改变它。

可以做些什么来实现所需?

1 个答案:

答案 0 :(得分:0)

您不得使用转换...但仅限

draggableControl.SetValue(Canvas.LeftProperty, X);
draggableControl.SetValue(Canvas.TopProperty, Y);

因为变换仅影响渲染