Automatic Scrolling in a Silverlight List Box

前端 未结 4 1240
情歌与酒
情歌与酒 2020-12-18 21:46

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

相关标签:
4条回答
  • 2020-12-18 22:02

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

    0 讨论(0)
  • 2020-12-18 22:07

    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);
            }
        }
    
    0 讨论(0)
  • 2020-12-18 22:18

    Slightly refactored to reduce the lines of code:

     listBoxEvents.Add(item)
     listBoxEvents.UpdateLayout()
     listBoxEvents.ScrollIntoView(listBoxEvents.Items(listBoxEvents.Items.Count - 1))
    
    0 讨论(0)
  • 2020-12-18 22:21

    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);
              }
          }                
     }
    
    0 讨论(0)
提交回复
热议问题