Automatic Scrolling in a Silverlight List Box

China☆狼群 提交于 2019-11-29 09:18:43

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

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

Slightly refactored to reduce the lines of code:

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

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);
          }
      }                
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!