Setting when to scroll in WPF ScrollViewer

柔情痞子 提交于 2019-12-10 20:40:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!