Joe Griffith
Joe Griffith

Reputation:

Automatic Scrolling in a Silverlight List Box

How can I programmatically force a silverlight list box to scroll to the bottom so that the last item added is always visible.

I've tried simply selecting the item. It ends up as selected but still not visible unless you manually scroll to it.

Upvotes: 14

Views: 12629

Answers (4)

Just went through this and none of the solutions above worked in a Silverlight 5 app. The solution turned out to be this:

 public void ScrollSelectedItemIntoView(object item)
 {
      if (item != null)
      {                
          FrameworkElement frameworkElement = listbox.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement;
          if (frameworkElement != null)
          {
              var scrollHost = listbox.GetScrollHost();                    
              scrollHost.ScrollIntoView(frameworkElement);
          }
      }                
 }

Upvotes: 0

David McSpadden
David McSpadden

Reputation: 449

Slightly refactored to reduce the lines of code:

 listBoxEvents.Add(item)
 listBoxEvents.UpdateLayout()
 listBoxEvents.ScrollIntoView(listBoxEvents.Items(listBoxEvents.Items.Count - 1))

Upvotes: 4

BrokeMyLegBiking
BrokeMyLegBiking

Reputation: 5988

The ScrollIntoView() method will scroll the last item into view, however listBox.UpdateLayout() must be called just before ScrollIntoView(). Here is a complete method with code:

    // note that I am programming Silverlight on Windows Phone 7

    public void AddItemAndScrollToBottom(string message)
    {
        string timestamp = DateTime.Now.ToString("mm:ss");
        var item = new ListBoxItem();
        item.Content = string.Format("{0} {1}", timestamp, message);
        // note that when I added a string directly to the listbox, and tried to call ScrollIntoView() it did not work, but when I add the string to a ListBoxItem first, that worked great
        listBoxEvents.Items.Add(item);

        if (listBoxEvents.Items.Count > 0)
        {
            listBoxEvents.UpdateLayout();
            var itemLast = (ListBoxItem)listBoxEvents.Items[listBoxEvents.Items.Count - 1];
            listBoxEvents.UpdateLayout();
            listBoxEvents.ScrollIntoView(itemLast);
        }
    }

Upvotes: 7

Bill Reiss
Bill Reiss

Reputation: 3460

Use the ListBox's ScrollIntoView method passing in the last item. You may need to call UpdateLayout immediately before it for it to work.

Upvotes: 24

Related Questions