在窗口周围移动控件

时间:2012-07-06 10:32:28

标签: c# wpf

所以我有Border TranslateTransform所以我可以在窗口移动它。在Border的内容中,我有许多控件和ScrollViewer。拖动工作正常,但是当我单击滚动条时,整个边框会跳转,以便我的光标现在位于我单击的最后一个点上方。非常烦人,我不明白为什么它会发生在我的滚动条上,而不是我的其他控件。

(我正在使用Denis Morozov简单,优秀的指南http://denismorozov.blogspot.ie/2008/01/drag-controls-in-wpf-using.html

这是我在代码中所做的事情;

private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
    {
        this.current.X = Mouse.GetPosition((IInputElement)sender).X;
        this.current.Y = Mouse.GetPosition((IInputElement)sender).Y;

        // Ensure object receives all mouse events.
        this.current.InputElement.CaptureMouse();
    }

    private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
    {
        if (this.current.InputElement != null)
            this.current.InputElement.ReleaseMouseCapture();
    }

    private void Canvas_MouseMove(object sender, MouseEventArgs e)
    {
        // if mouse is down when its moving, then it's dragging current
        if (e.LeftButton == MouseButtonState.Pressed)
            this.current.IsDragging = true;
        else
            this.current.IsDragging = false;

        if (this.current.IsDragging && current.InputElement != null)
        {
            // Retrieve the current position of the mouse.
            double newX = Mouse.GetPosition((IInputElement)sender).X;
            double newY = Mouse.GetPosition((IInputElement)sender).Y;

            // Reset the location of the object (add to sender's renderTransform

            // newPosition minus currentElement's position
            Transform rt = ((UIElement)this.current.InputElement).RenderTransform;
            double offsetX = rt.Value.OffsetX;
            double offsetY = rt.Value.OffsetY;
            rt.SetValue(TranslateTransform.XProperty, offsetX + newX - current.X);
            rt.SetValue(TranslateTransform.YProperty, offsetY + newY - current.Y);

            // Update position of the mouse
            current.X = newX;
            current.Y = newY;
        }
    }

    public void MouseLeftBtnDown(object sender, MouseButtonEventArgs e)
    {
        this.current.InputElement = (IInputElement)sender;
    }

1 个答案:

答案 0 :(得分:0)

实际上在Denis页面的评论中找到了它。问题在于不重置Canvas_MouseUp上的内容。那个方法实际应该是;

if (this.current.InputElement != null)
{
this.current.IsDragging = false;
this.current.InputElement.ReleaseMouseCapture();
this.current.InputElement = null;
}

现在就像魅力一样;)