gcoulby
gcoulby

Reputation: 544

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. 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. 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.

I think the reason has to do with the e.GetPosition(this).X; as 'this' refers to the Grid that is the rulers parent.

Do I need to commit the RenderTransform to the program? 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;
    }

Upvotes: 0

Views: 379

Answers (1)

MichaelN
MichaelN

Reputation: 156

Looks like Mouse.GetPosition doesn't work when dragging like you would expect.

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.

Upvotes: 1

Related Questions