【发布时间】:2009-05-29 21:18:49
【问题描述】:
如何以编程方式强制 Silverlight 列表框滚动到底部,以便始终可见最后添加的项目。
我试过简单地选择项目。它最终被选中,但仍然不可见,除非您手动滚动到它。
【问题讨论】:
-
+1 指出 Silverlight 如何遗漏了我能想象到的 ListBox 上最基本的功能。 WinForms 永远拥有它!可惜你现在还不是会员:)
标签: silverlight listbox
如何以编程方式强制 Silverlight 列表框滚动到底部,以便始终可见最后添加的项目。
我试过简单地选择项目。它最终被选中,但仍然不可见,除非您手动滚动到它。
【问题讨论】:
标签: silverlight listbox
使用 ListBox 的 ScrollIntoView 方法传入最后一项。您可能需要在 UpdateLayout 之前立即调用它才能使其工作。
【讨论】:
ScrollIntoView() 方法会将最后一项滚动到视图中,但是 listBox.UpdateLayout() 必须在 ScrollIntoView() 之前调用。这是一个完整的代码方法:
// 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);
}
}
【讨论】:
略微重构以减少代码行数:
listBoxEvents.Add(item)
listBoxEvents.UpdateLayout()
listBoxEvents.ScrollIntoView(listBoxEvents.Items(listBoxEvents.Items.Count - 1))
【讨论】:
刚刚完成此操作,上述解决方案均不适用于 Silverlight 5 应用程序。解决办法原来是这样的:
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);
}
}
}
【讨论】: