private void ImageShow_MouseWheel(object sender, MouseWheelEventArgs e) { var horizontalOffset = ImageScrollViewer.HorizontalOffset; var verticalOffset = ImageScrollViewer.VerticalOffset; if (e.Delta > 0) { double delta = 1.1; ImageShow.Width *= delta; ImageShow.Height *= delta; ImageScrollViewer.ScrollToHorizontalOffset(horizontalOffset * delta); ImageScrollViewer.ScrollToVerticalOffset(verticalOffset * delta); } else { if (e.Delta < 0) { double delta = 0.9; ImageShow.Width *= delta; ImageShow.Height *= delta; ImageScrollViewer.ScrollToHorizontalOffset(horizontalOffset * delta); ImageScrollViewer.ScrollToVerticalOffset(verticalOffset * delta); } } }
void OnScrollViewerScrollChanged(object sender, ScrollChangedEventArgs e) { if (e.ExtentHeightChange != 0 || e.ExtentWidthChange != 0) { Point?targetBefore = null; Point?targetNow = null; if (!_lastMousePositionOnTarget.HasValue) { if (_lastCenterPositionOnTarget.HasValue) { var centerOfViewport = new Point(ImageScrollViewer.ViewportWidth / 2, ImageScrollViewer.ViewportHeight / 2); var centerOfTargetNow = ImageScrollViewer.TranslatePoint(centerOfViewport, ImageGrid); targetBefore = _lastCenterPositionOnTarget; targetNow = centerOfTargetNow; } } else { targetBefore = _lastMousePositionOnTarget; targetNow = Mouse.GetPosition(ImageGrid); _lastMousePositionOnTarget = null; } if (targetBefore.HasValue) { var dXInTargetPixels = targetNow.Value.X - targetBefore.Value.X; var dYInTargetPixels = targetNow.Value.Y - targetBefore.Value.Y; var multiplicatorX = e.ExtentWidth / ImageGrid.Width; var multiplicatorY = e.ExtentHeight / ImageGrid.Height; var newOffsetX = ImageScrollViewer.HorizontalOffset - dXInTargetPixels * multiplicatorX; var newOffsetY = ImageScrollViewer.VerticalOffset - dYInTargetPixels * multiplicatorY; if (double.IsNaN(newOffsetX) || double.IsNaN(newOffsetY)) { return; } ImageScrollViewer.ScrollToHorizontalOffset(newOffsetX); ImageScrollViewer.ScrollToVerticalOffset(newOffsetY); } } }