WPF - 移动 Canvas

WPF - Moving a Canvas

我无法在 Window 中移动 canvas。

    <Canvas x:Name="Canvas1" Height="200" Grid.Column="1" Margin="10,15,92,54" Grid.Row="1" Background="#FFECECEC" Grid.RowSpan="2" MouseDown="Canvas_MouseDown" MouseUp="Canvas_MouseUp" MouseMove="Canvas_MouseMove" >
        <TextBox Height="100" Width="100" Margin="50,50,327,65" Background="Red"/>
        <TextBox Height="100" Width="100" Margin="10,15,327,65" Background="Blue" />
        <Canvas.RenderTransform>
            <TransformGroup>
                <TranslateTransform x:Name="translate" />
            </TransformGroup>
        </Canvas.RenderTransform>
    </Canvas>

这是隐藏代码:

    private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Canvas1.CaptureMouse();
        point = Mouse.GetPosition(Grid1);
    }

    private void Canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (Canvas1.IsMouseCaptured)
        {
            translate.X = e.GetPosition(Grid1).X - point.X;
            translate.Y = e.GetPosition(Grid1).Y - point.Y;
        }
    }

    private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
    {
        Canvas1.ReleaseMouseCapture();
    }

第一次,感觉还不错。 但是我第二次尝试点击我的 canvas,这个移动是从初始位置开始的。 我该如何解决?

在按下鼠标时初始化 point 时,减去当前翻译:

private void Canvas1_MouseDown(object sender, MouseButtonEventArgs e)
{
    Canvas1.CaptureMouse();
    point = Mouse.GetPosition(Grid1);
    point.X -= translate.X;
    point.Y -= translate.Y;
}

或者,总是只添加差异向量:

private void Canvas1_MouseDown(object sender, MouseButtonEventArgs e)
{
    Canvas1.CaptureMouse();
    point = Mouse.GetPosition(Grid1);
}

private void Canvas1_MouseMove(object sender, MouseEventArgs e)
{
    if (Canvas1.IsMouseCaptured)
    {
        var p = e.GetPosition(Grid1);
        var diff = p - point;
        point = p;

        translate.X += diff.X;
        translate.Y += diff.Y;
    }
}

同时通过将 Canvas 对齐方式设置为 Top/Left:

,确保网格不会定位 Canvas
<Canvas x:Name="Canvas1" HorizontalAlignment="Left" VerticalAlignment="Top" ...>

并且可能不设置 Margin,而是适当地初始化 TranslateTransform。