如何在拖动控件时将控件保留在其父控件中?

时间:2019-03-01 23:15:51

标签: c# wpf

因此,我有一个名为 UI_TileInformation 的控件,该控件需要保留在其父容器(画布)中,同时允许用户自由拖动它。 This solution有助于使其正常运行,现在可以完美拖动。但是,可以将其拖到其容器的边界之外。 This solution没有帮助,因为我看不到_transform变量的来源。

该控件具有以下默认变量:

protected bool isDragging;
private Point clickPosition;

以及这些事件处理程序:

this.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Control_MouseLeftButtonDown);
this.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(Control_MouseLeftButtonUp);
this.PreviewMouseMove += new MouseEventHandler(Control_MouseMove);

我对c#和WPF还是很陌生,但是我发现这些事件处理程序仅在预览时才可以使用(PreviewMouseMove而不是MouseMove)

关于使其拖动的代码,它类似于上面的第一个链接:

private void Control_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        isDragging = true;
        var draggableControl = sender as UI_TileInformation;
        clickPosition = e.GetPosition(this);
        draggableControl.CaptureMouse();
    }
private void Control_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        isDragging = false;
        var draggableControl = sender as UI_TileInformation;
        draggableControl.ReleaseMouseCapture();
    }
private void Control_MouseMove(object sender, MouseEventArgs e)
    {
        var draggableControl = sender as UI_TileInformation;

        if (isDragging && draggableControl != null)
        {
            Point positionInUIElement = e.GetPosition(this);

            var transform = draggableControl.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                draggableControl.RenderTransform = transform;
            }
            transform.X = positionInCanvas.X - clickPosition.X;
            transform.Y = positionInCanvas.Y - clickPosition.Y;
        }
    }

如何让我的控件留在画布内?

0 个答案:

没有答案