0

I'm using Thumb to resize an element. On DragDelta I'm doing myElement.Width += e.HorizontalChange. What if I want to resize it by multiplier of 100?

I tried myElement.Width += 100 * e.HorizontalChange but it causes the element to "dance" when I drag it. I assume it happens because of the big change that causes wrong calculation of mouse position relative to the element.

How it can be done?

UPDATE I recorded what I get. I resize the rectangle to the right and you can see how it flickering. The playback of the video is low but still you can see the flickering. It's much worse in reality.

theateist
  • 13,879
  • 17
  • 69
  • 109

1 Answers1

2

It looks that Thumb computes the HorizontalChange relative to itself rather than to the screen. So, if the thumb itself does not move accurately with the mouse while dragging, then HorizontalChange takes unreliable values. (Another example of such unwanted behavior)

So, it seems that Thumb is of a little help when implementing custom move/resize behavior. A "manual" handling of mouse movement is needed. Though, we can still use Thumb's events as convenient points to handle the mouse.

    FrameworkElement elementToResize;
    double initialWidth;
    Point initialMouse;

    private void Thumb_DragStarted(object sender, DragStartedEventArgs e)
    {
        initialWidth = elementToResize.ActualWidth;
        initialMouse = Mouse.GetPosition(Window.GetWindow((DependencyObject)sender));
    }

    private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
    {
        var horzChange = Mouse.GetPosition(Window.GetWindow((DependencyObject)sender)).X - initialMouse.X;
        elementToResize.Width = initialWidth + 100 * Math.Round(horzChange / 100);
    }

We need to compute mouse position change in the screen coordinates. This is not straightforward in WPF. Assuming that window is not moving on the screen while dragging the thumb, getting mouse position relative to the window will suit, as in the above code. For better reliability, you can get actual mouse screen coordinates, but this requires conversion from pixels to WPF device independent units.

Community
  • 1
  • 1
baSSiLL
  • 276
  • 2
  • 4
  • I don't see how it solves the problem. Anyway it still flickering. I recorded and updated my post. Please take a look – theateist Mar 25 '14 at 19:11
  • I thought your difficulty was with computing the stepping width correctly. Now I've tried with `Thumb` and also see this weird behavor. I've updated the answer. – baSSiLL Mar 26 '14 at 12:26
  • I has a similar issue for elements being scaled (the DragDelta goes crazy if the scale is less than 0.5). This solution worked but I had to keep updated the initialMouse position in Thumb_DragDelta, thanks – acaruci Feb 09 '16 at 16:37