ListBox如何移動到最底部

摘要:ListBox如何移動到最底部

當使用ListBox時,如果想讓裡面的scrollviewer移動到最後一項,可以使用這樣

this.listBox.SelectedIndex = this.listBox.Items.Count - 1;
this.listBox.ScrollIntoView(this.listBox.SelectedItem);

我原本也是寫成這樣,但是發現,ListBox的確是會移動,但是是移到最後一項的頭,我想要的是最後一項的尾!所以就找尋其他方式啦!然後發現Scrollviewer裡面有個ScrollToVerticalOffset這個可以用,但是,要怎麼去取得ListBox裡的ScrollViewer呢?用下面這個就可以得到啦~

        public 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 <= i; i--)
                {
                    var child = VisualTreeHelper.GetChild(current, i);
                    var typedChild = child as T;
                    if (typedChild != null)
                    {
                        return typedChild;
                    }
                    queue.Enqueue(child);
                }
            }
            return null;
        }

然後再把最前面的Code改寫成

            var scroller = FindChildOfType(this.listBox);
            scroller.ScrollToVerticalOffset(this.listBox.Height);

這麼一來,就真的是移到最底部了!

 

囧....這邊的code區塊會自動幫我加上奇怪的東西(</dependencyobject></t>)...請各位不要理它..OTL