简体   繁体   中英

How to resize element by multiplier of X with Thumb in WPF?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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