WPF中ListBox滚动条自动滚动

时间:2020-12-24 07:54:07

开始以为设置listbox的SelectedIndex或者SelectedItem就可以了,结果并没有什么卵用

需要通过可视树找到listbox里面的那个ScrollViewer,然后通过ScrollToEnd滚动到最后

DataSource.CollectionChanged += ListBox_SourceUpdated;
private void ListBox_SourceUpdated(object sender, EventArgs e)
{
    Decorator decorator = (Decorator)VisualTreeHelper.GetChild(listBox, 0);
    ScrollViewer scrollViewer = (ScrollViewer)decorator.Child;
    scrollViewer.ScrollToEnd();
}