flamebaud
flamebaud

Reputation: 998

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?

Upvotes: 3

Views: 875

Answers (2)

flamebaud
flamebaud

Reputation: 998

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);
}

Upvotes: 1

Rikki
Rikki

Reputation: 3538

I think you should write a custom control that implements IScrollInfo interface and customize the calculation of provided values by the interface.

Take a look at this: http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.iscrollinfo.aspx

Upvotes: 0

Related Questions