当设置在WPF ScrollViewer的滚动WPF、ScrollViewer

2023-09-04 13:42:41 作者:只是喜歡你

我有一个包含在这一堆表单控件(文本框,复选框,组合框等),一个网格的ScrollViewer。当我在控制选项卡中,将ScrollViewer的滚动,但只有当必要的。我的意思是我选项卡通过在ScrollViewer中的所有内容只有当控件不可见请问ScrollViewer的滚动。我想做到的是具有ScrollViewer的滚动当控制在可见区域的底部25%,随后向上滚动时,控制在可见区域的顶部25%(逆跳格)。实现这一点?

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?

推荐答案

我发现这个问题是处理GotFocus事件的表单控件的最佳解决方案。由于我生成一个公共区域的控制,很容易分配此创建所有控件。在此事件处理程序,我找到元件的其含有网格内的位置。然后我做了ScrollToVerticalOffset上的滚动浏览器,计算的ScrollViewer的一半,呈现高度的减法。这样可以使在ScrollViewer中如果可能的中间的主动控制。

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