You need to get hold of the ScrollViewer
that is used by the ListBox
internally so you can grab the value of the VerticalOffset
property and subsequently call the SetVerticalOffset
method.
This requires that you reach down from the ListBox
through the Visual tree that makes up its internals.
I use this handy extension class which you should add to your project (I've gotta put this up on a blog because I keep repeating it):-
public static class VisualTreeEnumeration
{
public static IEnumerable<DependencyObject> Descendents(this DependencyObject root, int depth)
{
int count = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(root, i);
yield return child;
if (depth > 0)
{
foreach (var descendent in Descendents(child, --depth))
yield return descendent;
}
}
}
public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
{
return Descendents(root, Int32.MaxValue);
}
public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
{
DependencyObject current = VisualTreeHelper.GetParent(root);
while (current != null)
{
yield return current;
current = VisualTreeHelper.GetParent(current);
}
}
}
With this available the ListBox
(and all other UIElements for that matter) gets a couple of new extension methods Descendents
and Ancestors
. We can combine those with Linq to search for stuff. In this case you could use:-
ScrollViewer sv = SomeListBox.Descendents().OfType<ScrollViewer>().FirstOrDefault();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…