Robot Mess
Robot Mess

Reputation: 959

Detect user originated scroll in WPF

How can I detect a user originated scroll event in WPF? By user originated scroll I mean a scroll event caused by the mouse click on the scroll bar or by the user using the context menu of the scroll bar like in the screenshot.

enter image description here

The reason I want to know this is: I want to deactivate the autoscroll functionality that I have implemented when the user want to take manual control of the scroll position. The ListView that automatically scrolls down to the newly added elements by calling ScrollIntoView, should stop this behavior when the user does any manual scrolling.

Upvotes: 2

Views: 2283

Answers (1)

Robot Mess
Robot Mess

Reputation: 959

As Sinatr suggested, I created a flag that remembers if a ScrollIntoView has been triggered. This solution seems to work just fine, but needed some handling of the ScrollChangedEventArgs

The relevant bits are in scrollViewer_ScrollChanged, but I provided a bit more code for context, The autoscroll is deactivated when the user tries to scroll up, and reactivated when he scrolls to the bottom.

private volatile bool isUserScroll = true;
public bool IsAutoScrollEnabled { get; set; }

// Items is the collection with the items displayed in the ListView

private void DoAutoscroll(object sender, EventArgs e)
{
    if(!IsAutoScrollEnabled)
        return;
    var lastItem = Items.LastOrDefault();
    if (lastItem != null)
    {
        isUserScroll = false;
        logView.ScrollIntoView(lastItem);
    }
}

private void scrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
    if (e.VerticalChange == 0.0)
        return;

    if (isUserScroll)
    {
        if (e.VerticalChange > 0.0)
        {
            double scrollerOffset = e.VerticalOffset + e.ViewportHeight;
            if (Math.Abs(scrollerOffset - e.ExtentHeight) < 5.0)
            {
                // The user has tried to move the scroll to the bottom, activate autoscroll.
                IsAutoScrollEnabled = true;
            }
        }
        else
        {
            // The user has moved the scroll up, deactivate autoscroll.
            IsAutoScrollEnabled = false;
        }
    }
    isUserScroll = true;
}

Upvotes: 3

Related Questions