Search code examples
c#windows-phone-8longlistselector

Scroll LongListSelector when new item added


I have a chat application that shows messages in a LongListSelector and adds new ones with the statement ObservableCollection.Insert(0, message).

My issue is that when a new message is added, the LongListSelector doesn't scroll down to the new message.

The best solution in my opinion would be to automatically scroll to new messages if the LongListSelector is currently scrolled to the top, but I cannot find a method to detect current scrolling position (I see only LongListSelector.ScrollTo(), which isn't helpful).

How can I automatically scroll to new messages when the LongListSelector is currently scrolled to the top?


Solution

  • If you need to find current scroll position than you need to get the scrollbar inside longlistselector using VisualTreeHelper.

    The sample function:

    public static class VisualChildExtractHelper
    {
    
      public static T FindChildOfType<T>(DependencyObject root) where T : class
      {
        var queue = new Queue<DependencyObject>();
        queue.Enqueue(root);
    
        while (queue.Count > 0)
        {
            DependencyObject current = queue.Dequeue();
            for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
            {
                var child = VisualTreeHelper.GetChild(current, i);
                var typedChild = child as T;
                if (typedChild != null)
                {
                    return typedChild;
                }
                queue.Enqueue(child);
            }
        }
        return null;
      }
    }
    

    usage:

    ScrollBar LongListSelectorScrollBar = VisualChildExtractHelper.FindChildOfType<ScrollBar>(yourLongListSelectorName);
    

    After that you can access ScrollBar Value (or ValueChanged event) and check if it equals 0 (that means that longlistselector is scrolled to the top) or other condition. If it is you can ScrollTo method of LongListSelector to bring element into view.