简体   繁体   English

C#WPF RenderTransform在按下鼠标时重置

[英]C# WPF RenderTransform resets on mousedown

I am having a problem with this code. 我对此代码有疑问。 When I start the program Ruler is in the center of the page. 当我启动程序时,标尺位于页面的中心。 When I mousemove when MouseDown is true, the Rectangle (Ruler) is dragable as I want. 当MouseDown为true时,我进行mousemove时,可以根据需要拖动Rectangle(Ruler)。 However, this only works on the first drag. 但是,这仅在第一次拖动时起作用。 The next time I go to drag it the Ruler jumps back to it's original position, then when you mouse over it the distance from where it was to where it jumped back is calculated and it jumps off the screen as the mouseup event doesn't fire as the rectangle has moved. 下次我拖动它时,标尺跳回到其原始位置,然后将鼠标悬停在它上面时,将计算出它从原处到跳回位置的距离,并且由于mouseup事件不会触发,它会跳出屏幕随着矩形的移动。 I basically want to be able to drag the object around the screen however many times I want, but the XStart and YStart need to take the new rendered values on each click. 我基本上希望能够将对象在屏幕上拖动很多次,但是XStart和YStart每次单击都需要采用新的渲染值。

I think the reason has to do with the e.GetPosition(this).X; 我认为原因与e.GetPosition(this).X;有关; as 'this' refers to the Grid that is the rulers parent. 如“ this”是指作为标尺父级的网格。

Do I need to commit the RenderTransform to the program? 我需要将RenderTransform提交给程序吗? or is there an error in my logic? 还是我的逻辑有误?

It would honestly make more sense if it didn't work at all, but to work perfectly once, then screw up makes no sense. 老实说,如果它根本不起作用,那会更有意义,但是一次完美地工作,然后搞砸就没有意义了。

Here is the code: 这是代码:

    private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
    {
        XStart = e.GetPosition(this).X;
        YStart = e.GetPosition(this).Y;

        Console.WriteLine("X: " + XStart + ", Y: " + YStart);

        MouseDown = true;

    }

    private void Rectangle_MouseMove(object sender, MouseEventArgs e)
    {

        if(MouseDown)
        {
            X = e.GetPosition(this).X - XStart;
            Y = e.GetPosition(this).Y - YStart;

            Ruler.RenderTransform = new TranslateTransform(X, Y);
        }
    }

    private void Ruler_MouseUp(object sender, MouseButtonEventArgs e)
    {
        MouseDown = false;
    }

Looks like Mouse.GetPosition doesn't work when dragging like you would expect. 看起来像Mouse.GetPosition在拖动时像您期望的那样不起作用。

This example seems relevant, but he uses the DragOver event instead of MouseMove, so I'm not entirely sure if it's the same situation. 这个示例似乎很相关,但是他使用DragOver事件而不是MouseMove,因此我不确定是否是同样的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM