Search code examples
c#.netwpfmulti-touch

WPF: Dragging an Element via Touch is pretty choppy


I have a Rectangle which can be dragged within some boundaries. This works perfect with the mouse.

As soon as I set IsManipulationEnabled to true the mouse-events don't work anymore. However I need this to get touch-events on the rectangle. Therefore I set it to true.

I'm trying to compute all changes in the ManipulationDelta-event like in the following function. Scaling works already pretty good, but moving the object via dragging it with the finger is very choppy + plus sometimes the Rectangle jumps back and forth.

private void UserControl_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    //Scaling works already pretty good
    RangeBar.Width *= e.DeltaManipulation.Scale.X;

    //Moving the element is very choppy, what am I doing wrong here?
    this.startX = this.startX + e.DeltaManipulation.Translation.X;
    RangeBar.SetValue(Canvas.LeftProperty, startX);
}

Solution

  • I'd try using the CumulativeManipulation instead.

    Whenever I need to do a UI element movement via dragging, I don't try to reuse the same variable and modify it by the delta and then reuse that same variable for setting position. It almost always gives me stability issues regardless of platform. Instead, try storing a variable when dragging starts and adding the delta to that variable only when you need to update position. So something more like this:

    Point origin;
    
    void MouseDown(Point location)
    {
       origin = location;
    }
    
    void MouseDrag(Vector cumulativeOffset)
    {
       SetControlLocation(origin+cumulativeOffset);
    }
    

    Also, what's the source of the ManipulationEvent? You'll definitely want to make sure it's not the current rectangle, or that will definitely cause the issues you're seeing.