问题
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?
回答1:
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);
}
回答2:
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
来源:https://stackoverflow.com/questions/12299739/setting-when-to-scroll-in-wpf-scrollviewer