none
wpf listbox滚动后如何知道当前能够看到的是那些项 RRS feed

  • 问题

  • listbox有大概20个item,而它content不能完全包括的Item。这样就出现滚动条,想知道滚动后,当前能够看见的Item是那些,如5-15项。

    还有如何判断Listbox滚动到末尾了

    2013年11月6日 8:29

答案

  • 你好,

    首先,我们可以通过视图树找到ListBox的ScrollViewer:

    // Get the border of the listview (first child of a listview)
    Decorator border = VisualTreeHelper.GetChild(listbox, 0) as Decorator;
    if (border != null)
    {
            // Get scrollviewer
            ScrollViewer scrollViewer = border.Child as ScrollViewer;
     if (scrollViewer != null)
            {
                    /* Something
                     */
            }
    }

    找到ScrollViewer后,可以通过比较VerticalOffset和ScrollableHeight大小来判断是否滚动到末尾:

    if (scrollViewer.VerticalOffset >= scrollViewer.ScrollableHeight)
            MessageBox.Show("Bottom");

    通过VerticalOffset计算当前显示的项:

    int firstitem = Convert.ToInt32(1 + scrollViewer.VerticalOffset);
    int lastitem = (7 + scrollViewer.VerticalOffset) > 20 ? 20 : Convert.ToInt32(7 + scrollViewer.VerticalOffset);
    tb3.Text = firstitem.ToString() + " - " + lastitem.ToString();

    运行截图:

    通过以下链接下载示例工程:
    http://sdrv.ms/1dOYwPo

    参考资料:
    #ScrollViewer.VerticalOffset Property
    http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.verticaloffset(v=vs.110).aspx

    #ScrollViewer.ScrollableHeight Property
    http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.scrollableheight.aspx


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • 已标记为答案 skczjun 2013年11月11日 0:41
    2013年11月7日 8:41
    版主