【问题标题】:Automatic Scrolling in a Silverlight List BoxSilverlight 列表框中的自动滚动
【发布时间】:2009-05-29 21:18:49
【问题描述】:

如何以编程方式强制 Silverlight 列表框滚动到底部,以便始终可见最后添加的项目。

我试过简单地选择项目。它最终被选中,但仍然不可见,除非您手动滚动到它。

【问题讨论】:

  • +1 指出 Silverlight 如何遗漏了我能想象到的 ListBox 上最基本的功能。 WinForms 永远拥有它!可惜你现在还不是会员:)

标签: silverlight listbox


【解决方案1】:

使用 ListBox 的 ScrollIntoView 方法传入最后一项。您可能需要在 UpdateLayout 之前立即调用它才能使其工作。

【讨论】:

  • 这正是我一直在寻找的答案......我无法让它工作。看起来这应该有效... If lst.Items.Count > 0 Then lst.SelectedIndex = lst.Items.Count - 1 lst.ScrollIntoView(lst.SelectedItem) lst.UpdateLayout() Else 最后一个项目被选中但没有可见。
  • 在 ScrollIntoView 之前调用 UpdateLayout,希望对你有用。
  • 成功了。完全按照我现在想要的方式工作。谢谢。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    略微重构以减少代码行数:

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

    【讨论】:

      【解决方案4】:

      刚刚完成此操作,上述解决方案均不适用于 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);
                }
            }                
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多