简体   繁体   中英

WPF - How to autoscroll scrollviewer when it need to scroll?

Let me try to explain what my requirement is, first of all, here's a form with 50 fields, at the start, cursor is in the first field TextBox:

在此处输入图片说明

When I filled 10 fields, cursor now will be in Field11:

在此处输入图片说明

Now, I want the scroll will autoscroll to a location like this when I focused in Field11 for more view:

在此处输入图片说明

So if anybody understand what I'm talking about, would you please help me to solve this? Thanks!

You can use ScrollChangedEventArgs.ExtentHeightChange to know if a ScrollChanged is due to a change in the content or to a user action... When the content is unchanged, the ScrollBar position sets or unsets the autoscroll mode. When the content havs changed you can apply autoscrolling.

Code behind:

private Boolean AutoScroll = true;

private void ScrollViewer_ScrollChanged(Object sender, ScrollChangedEventArgs e)
{
    // User scroll event : set or unset autoscroll mode
    if (e.ExtentHeightChange == 0)
    {   // Content unchanged : user scroll event
        if (ScrollViewer.VerticalOffset == ScrollViewer.ScrollableHeight)
        {   // Scroll bar is in bottom
            // Set autoscroll mode
            AutoScroll = true;
        }
        else
        {   // Scroll bar isn't in bottom
            // Unset autoscroll mode
            AutoScroll = false;
        }
    }

    // Content scroll event : autoscroll eventually
    if (AutoScroll && e.ExtentHeightChange != 0)
    {   // Content changed and autoscroll mode set
        // Autoscroll
        ScrollViewer.ScrollToVerticalOffset(ScrollViewer.ExtentHeight);
    }
}

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