How can I make ScrollViewer scroll my Canvas smoothly in code (no xaml)? As I know for xaml it needs to set ScrollUnit to "Pixel", but I can't do it in code.

1 Answers

Mertus On Best Solutions

If what you are after is moving the scroll one pixel with each mouse wheel turn here is the way.

Register to mouse wheel preview event.

<ScrollViewer Height="350" Width="525" PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
    <Canvas Height="650" Width="510">
        <Button Name="b" Height="30" Width="525" Content="Button text"/>

Move the scroll by 1 pixel on each time the event fires and set it as handled.

private void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
    ScrollViewer scrollViewer = sender as ScrollViewer;
    double offset = scrollViewer.VerticalOffset - Math.Sign(e.Delta);
    scrollViewer.ScrollToVerticalOffset(Math.Min(Math.Max(offset, 0), scrollViewer.ExtentHeight));
    e.Handled = true;