Search code examples
c#windowswindows-phone-8windows-phone-8.1windows-phone

How to find the position of an item within a ScrollViewer (ListView)?


I have a ListView, and I want to find the offset for a particular item so I can later center it on my listView, scrolling to the correspondent vertical offset.

So far I found no way to retrieve the position (offset) of an item within a ScrollViewer.


Solution

  • There is a way to find an item position (offset) within a ScrollViewer.

    If you are looking for the item offset in a ListView, you first have to get the ScrollViewer inside the ListView:

    ScrollViewer scrollViewer = GetScrollViewer(MyListView);
    
    public static ScrollViewer GetScrollViewer(DependencyObject depObj)
    {
        var obj = depObj as ScrollViewer;
        if (obj != null) return obj;
    
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            var child = VisualTreeHelper.GetChild(depObj, i);
    
            var result = GetScrollViewer(child);
            if (result != null) return result;
        }
        return null;
    }
    

    This way you will have access to the ScrollViewer. If you have a set of items within a ListView, you will also have to get the container (FrameworkElement) regarding the item.

    var container = MyListView.ContainerFromItem(myItemInListView);
    

    If you already have your container you can then proceed to the following code:

    FrameworkElement element = container as FrameworkElement;
    if (element != null)
    {
        var transform = element.TransformToVisual(viewer);
        var positionInScrollViewer = transform.TransformPoint(new Point(0, 0));
    }
    

    The positionInScrollViewer object will be a point so, you can get the verticalOffset by accessing positionInScrollViewer.Y, or if you are dealing with a horizontal ScrollViewer you should access positionInScrollViewer.X and you will have the offset for the desired object/item.