WPF中ListBox滚动条保持在最底部无效的问题
最近在使用listbox的过程中遇到了一个很恶心的问题,就是我的listbox的滚动条无法一直保持在底部,作为一个信息提示控件,这对用户来说非常不友好。在网上搜索了相关方法:
1.设置TopIndex属性
this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);
2.使用ScrollIntoView方法:目前重写控件和重写控件的properties基本都是用的这个
host.ScrollIntoView(host.SelectedItem);
以上2种方法,我都试了,都没有实现,直到今天,我终于找到了解决办法:
先获取到ListBox控件内部的ScrollViewer控件,然后再使用ScrollToBottom方法,相关代码如下:
代码参考了:https://www.cnblogs.com/chuhaida/p/3724776.html
public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
if (obj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}
ScrollViewer scroll = FindVisualChild<ScrollViewer>(RadListBox);
scroll.ScrollToBottom();