Windows Phone开发,ListBox滚到底部刷新的方法

原理:通过传入的参数(ListBox),遍历其子控件,找到垂直方向的ScrollBar,再通过ValueChanged事件根据其ValueProperty(当前值)和MaximumProperty(最大值)判断是否滚到底.
取ScrollBar的方法:


        private static ScrollBar GetVerticalScrollBar(DependencyObject parent)
        {
            List listScrollBar = new List();
            ListverticalScrollBar(parent, listScrollBar);
            //遍历子控件,如果是垂直方向的ScrollBar,则加入List
            if (listScrollBar.Count > 0)
            {//一个控件肯定最多只有一个垂直的ScrollBar,所以返回第一个就行
                return listScrollBar.ElementAt(0);
            }
            return null;
        }
        private static void ListverticalScrollBar(DependencyObject parent, List listScrollBar)
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            //取子控件数量,
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                //逐个取出,看其是否是ScrollBar
                if (child is ScrollBar)
                {
                    ScrollBar scrollBar = (ScrollBar)child;
                    if (scrollBar.Orientation == System.Windows.Controls.Orientation.Vertical)
                    {//看其方向是否是垂直
                        listScrollBar.Add(scrollBar);
                    }
                }
                else if (child != null)
                {//如果不是ScrollBar,且不为空,递归
                    ListverticalScrollBar(child,listScrollBar);
                }
            }
        }

调用方法:


ScrollBar scrollBar1 = GetVerticalScrollBar(FirstListBox);
if (scrollBar1 != null)
{
    scrollBar1.ValueChanged += new RoutedPropertyChangedEventHandler(verticalScrollBar_ValueChanged);
}

verticalScrollBar_ValueChanged方法:


        private void verticalScrollBar_ValueChanged(object sender, RoutedEventArgs e)
        {

            ScrollBar scrollBar = (ScrollBar)sender;
            object valueObj = scrollBar.GetValue(ScrollBar.ValueProperty);
            object maxObj = scrollBar.GetValue(ScrollBar.MaximumProperty);
            if (valueObj != null && maxObj != null)
            {
                double value = (double)valueObj;
                double max = (double)maxObj;
                System.Diagnostics.Debug.WriteLine("value" + value + " max" + max);
                if (Math.Abs(value - max) < 0.00001)
                {//浮点数无法保存精确值,只能相减,小于某个精度来判断
                   
                }
            }
        }

好像ListBox没有数据进是取不到ScrollBar的,所以需要ListBox有数据后(添加第一页以后)再调用

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记