Automatic Scrolling in a Silverlight List Box

前端 未结 4 1245
情歌与酒
情歌与酒 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: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);
            }
        }
    

提交回复
热议问题