Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting when to scroll in WPF ScrollViewer

I have a scrollviewer that contains a grid with a bunch of form controls in it (textboxes, checkboxes, comboboxes, etc). When I tab through the controls, the scrollviewer will scroll, but only when necessary. By this I mean I tab through all the content in the scrollviewer and only when the control is not visible does the scrollviewer scroll. What I would like to accomplish is having the scrollviewer scroll down when the control is in the bottom 25% of the visible area, and subsequently scroll up when the control is in the top 25% of the visible area (reverse tabbing). Can this be accomplished?

like image 982
flamebaud Avatar asked May 29 '26 01:05

flamebaud


1 Answers

The best solution I found for this problem was to handle the GotFocus event for the form controls. Since I generate the controls in a common area, it was easy to assign this to all controls created. In this event handler, I locate the position of the element within its containing grid. I then do a ScrollToVerticalOffset on the scroll viewer, calculating a subtraction of half the render height of the scrollviewer. This keeps the active control in the middle of the scrollviewer if possible.

void FormElement_GotFocus(object sender, RoutedEventArgs e)
{
    FormElement element = sender as FormElement;
    Point elementLocation = element.TranslatePoint(new Point(), canvasGrid);
    double finalHeight = elementLocation.Y - (canvasScrollViewer.RenderSize.Height/2);
    canvasScrollViewer.ScrollToVerticalOffset(finalHeight);
}
like image 131
flamebaud Avatar answered May 30 '26 13:05

flamebaud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!