如何将WPF ScrollViewer的内容滚动到特定位置

时间:2011-06-13 21:13:49

标签: wpf mouse position scrollviewer

我正在编写自定义WPF ItemsControl以显示项目列表。这些项目显示在ScrollViewer中:

<Style TargetType="MyCustomItemsControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="MyCustomItemsControl">
                    <ScrollViewer x:Name="PART_MyScrollViewer" >
                           <ItemsPresenter/>
                    </ScrollViewer>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
</Style>

我想确保当我将鼠标移动到控件中时,特定项目(标记为已选中)将滚动到鼠标位置。在我的OnMouseEnter方法中,我能够找到该项目,但我不知道下一步该做什么。有没有人有任何想法?

protected override void OnMouseEnter(MouseEventArgs e)
{
    for (int i = 0; i < Items.Count; i++)
    {
        ContentPresenter uiElement = (ContentPresenter)ItemContainerGenerator.ContainerFromIndex(i);
        var item = uiElement.Content as MyCustomObject;
        if (item.IsSelected)
        {
            // How to scroll the uiElement to the mouse position?
            break;
        }
    }
}

4 个答案:

答案 0 :(得分:20)

如下所示:

var sv = (ScrollViewer)Template.FindName("PART_MyScrollViewer", this); // If you do not already have a reference to it somewhere.
var ip = (ItemsPresenter)sv.Content;
var point = item.TranslatePoint(new Point() - (Vector)e.GetPosition(sv), ip);
sv.ScrollToVerticalOffset(point.Y + (item.ActualHeight / 2));

答案 1 :(得分:18)

// How to scroll the uiElement to the mouse position?
uiElement.BringIntoView();

参考:https://msdn.microsoft.com/en-us/library/ms598110.aspx

更新:(感谢@jmbpiano)注意,它不会将控件精确地带到当前鼠标光标位置。它只是将控件带到一个可见的位置,操作员可以用鼠标点击它(在99%的情况下,所有人都可能需要这个问题)。

答案 2 :(得分:8)

使用UIElement.TranslatePoint()计算要滚动到的位置

使用ScrollViewer.ScrollToVerticalOffset()进行滚动

答案 3 :(得分:0)

请尝试以下代码:


private void ScrollViewerFromVSTree(DependencyObject element, double pos)
{
    try
    {
        int totalElementcount = VisualTreeHelper.GetChildrenCount(element);
        for (int counter = 0; counter < totalElementcount; counter++)
        {
            DependencyObject ele = VisualTreeHelper.GetChild(element, counter);
            if (ele.GetType().Name == "ScrollViewer")
            {
                ScrollViewer scrollViewer = ele as ScrollViewer;
                if (pos > "YourAssumption") // for me it is 610
                {
                    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + 45);
                }
                else if (pos < "YourAssumption") //for me it is 40
                {
                    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - 45);
                }
                break;
            }
            ScrollViewerFromVSTree(VisualTreeHelper.GetChild(element, counter), pos);
        }
    }
    catch (Exception)
    {
    }
}