tonwei139 发表于 2015-5-9 10:18:05

Windows Phone 7 如何判断ListBox控件滚动到底

假如ListBox控件绑定的数据很大的时候,通常会造成加载的速度很慢,那么有一种交互方案可以优化一下这种情况,就是先在ListBox上加载一部分的数据,等到用户查看的时候将ListBox滚动到底的时候再加载一部分数据。但是在ListBox控件里面根本就没有相关的事件和属性来判断出来ListBox什么时候滚动到底了,那么下面讲解一种解决的方法。

   ListBox控件其实是封装了ScrollViewer控件和ScrollBar控件在里面的。那这就好办了,通过获取ListBox控件里面封装的ScrollViewer控件,然后通过ScrollViewer控件的属性就可以判断出来ListBox控件是否滚动到底了。

下面看一下代码:






            
            
      





using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Phone.Controls;
namespace ListBoxUpdate
{
    public partial class MainPage : PhoneApplicationPage
    {
      public MainPage()
      {
            InitializeComponent();
            for (int i = 0; i < 30; i++)
            {
                listbox1.Items.Add("项目"+i);
            }
      }
      private void listbox1_MouseMove(object sender, MouseEventArgs e)
      {
            //获取listbox的子类型ScrollViewer
            ScrollViewer scrollViewer = FindChildOfType(listbox1);//ScrollViewerscrollBar
            if (scrollViewer == null)
            {
                throw new InvalidOperationException("erro");
            }
            else
            {
                //判断当前滚动的高度是否大于或者等于scrollViewer实际可滚动高度,如果等于或者大于就证明到底了
                if (scrollViewer.VerticalOffset >= scrollViewer.ScrollableHeight)
                {
                  //处理listbox滚动到底的事情
                  for (int i = 0; i < 10; i++)
                  {
                        int k = listbox1.Items.Count;
                        listbox1.Items.Add("项目" + k);
                        k++;
                  }
                }
            }
      }
      //获取子类型
      static T FindChildOfType(DependencyObject root) where T : class
      {
            var queue = new Queue();
            queue.Enqueue(root);
            while (queue.Count > 0)
            {
                DependencyObject current = queue.Dequeue();
                for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0
页: [1]
查看完整版本: Windows Phone 7 如何判断ListBox控件滚动到底